File: TextFinderSemi.m

package info (click to toggle)
gtamsanalyzer.app 0.42-6
  • links: PTS
  • area: main
  • in suites: squeeze, wheezy
  • size: 6,112 kB
  • ctags: 866
  • sloc: objc: 34,338; ansic: 8,762; cpp: 384; makefile: 59; sh: 47
file content (924 lines) | stat: -rwxr-xr-x 36,843 bytes parent folder | download | duplicates (7)
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
/*
        TextFinder.m
        Copyright (c) 1995-2001 by Apple Computer, Inc., all rights reserved.
        Author: Ali Ozer

        Find and replace functionality with a minimal panel...
        Would be nice to have the buttons in the panel validate; this would allow the 
            replace buttons to become disabled for readonly docs
*/
/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation, 
 modification or redistribution of this Apple software constitutes acceptance of these 
 terms.  If you do not agree with these terms, please do not use, install, modify or 
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and subject to these 
 terms, Apple grants you a personal, non-exclusive license, under Apples copyrights in 
 this original Apple software (the "Apple Software"), to use, reproduce, modify and 
 redistribute the Apple Software, with or without modifications, in source and/or binary 
 forms; provided that if you redistribute the Apple Software in its entirety and without 
 modifications, you must retain this notice and the following text and disclaimers in all 
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks 
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from 
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your 
 derivative works or by other works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES, 
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, 
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS 
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL 
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, 
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND 
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR 
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Regular expression code added 3/11/2003 by Matthew Weinstein for the TAMS Analyzer project
*/

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "TextFinder.h"
#import "AGRegex.h"
#import "utils.h"
#define COUNTSTRING @"REGEXCOUNT"
//#define oldReplaceREGEX 1
#define oneAtATimeReplaceRegex 1
@interface AGRegex (NSEscapeReplace)
- (NSString *)replaceWithString:(NSString *)rep inString:(NSString *)str limit:(int)lim range: (NSRange) r;

- (NSString *)replaceWithStringWithEscape:(NSString *)rep inString:(NSString *)str;
- (NSString *)replaceWithStringWithEscape:(NSString *)rep inString:(NSString *)str limit: (int) lim range: (NSRange) r;
@end


@interface NSString (NSStringTextFinding)

- (NSRange)findString:(NSString *)string selectedRange:(NSRange)selectedRange options:(unsigned)mask wrap:(BOOL)wrapFlag regex: (BOOL) regexFlag multiline: (BOOL) mlFlag;

@end


@implementation TextFinder

static id sharedFindObject = nil;

+ (id)sharedInstance {
    if (!sharedFindObject) {
        [[self allocWithZone:[[NSApplication sharedApplication] zone]] init];
    }
    return sharedFindObject;
}

- (id)init {
    if (sharedFindObject) {
        [super dealloc];
        return sharedFindObject;
    }

    if (!(self = [super init])) return nil;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidActivate:) name:NSApplicationDidBecomeActiveNotification object:[NSApplication sharedApplication]];

    [self setFindString:@"" writeToPasteboard:NO];
    [self loadFindStringFromPasteboard];

    sharedFindObject = self;
    return self;
}

- (void)appDidActivate:(NSNotification *)notification {
    [self loadFindStringFromPasteboard];
}

- (void)loadFindStringFromPasteboard {
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSFindPboard];
    if ([[pasteboard types] containsObject:NSStringPboardType]) {
        NSString *string = [pasteboard stringForType:NSStringPboardType];
        if (string && [string length]) {
            [self setFindString:string writeToPasteboard:NO];
        }
    }
}

- (void)loadFindStringToPasteboard {
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSFindPboard];
    [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
    [pasteboard setString:[self findString] forType:NSStringPboardType];
}

- (void)loadUI {
    if (!findTextField) {
        if (![NSBundle loadNibNamed:@"FindPanel" owner:self])  {
            NSLog(@"Failed to load FindPanel.nib");
            NSBeep();
        }
	if (self == sharedFindObject) [[findTextField window] setFrameAutosaveName:@"Find"];
    }
    [findTextField setStringValue:[self findString]];
}

- (void)dealloc {
    if (self != sharedFindObject) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [findString release];
        [super dealloc];
    }
}

- (NSString *)findString {
    return findString;
}

- (void)setFindString:(NSString *)string {
    [self setFindString:string writeToPasteboard:YES];
}

-(NSString *) getFindString
{
    return [self convertEscapeString: [findTextField stringValue]];
}
-(NSString *) getReplaceString
{
    return [self convertEscapeString: [replaceTextField stringValue]];
}
-(NSString *)convertEscapeString: (NSString *) oString
{
   int n, i;
    unichar ch, chn;
    NSMutableString *newString = [[NSMutableString alloc] init];
    //go through the replace string
    n = [oString length];
    for(i = 0; i < n; i++)
    {
        ch = [oString characterAtIndex: i];
        if(ch == '\\' && i < n - 1)
        {
            chn = [oString characterAtIndex: ++i];
            switch(chn)
            {
                case 't':
                    [newString ADDCHAR('\t')];
                    break;
                case 'n':
                    [newString ADDCHAR('\n')];
                    break;
                case 'r':
                    [newString ADDCHAR('\r')];
                    break;
                default:
                    [newString ADDCHAR('\\')];
                    [newString ADDCHAR(chn)];
                    break;
            }
        }
        else
            [newString ADDCHAR( ch)];
    }
    [newString autorelease];
    return newString;

}

- (void)setFindString:(NSString *)string writeToPasteboard:(BOOL)flag {
    if ([string isEqualToString:findString]) return;
    [findString autorelease];
    findString = [string copyWithZone:[self zone]];
    if (findTextField) {
        [findTextField setStringValue:string];
        [findTextField selectText:nil];
    }
    if (flag) [self loadFindStringToPasteboard];
}

- (NSTextView *)textObjectToSearchIn {
    id obj = [[NSApp mainWindow] firstResponder];
    return (obj && [obj isKindOfClass:[NSTextView class]]) ? obj : nil;
}

- (NSPanel *)findPanel {
    if (!findTextField) [self loadUI];
    return (NSPanel *)[findTextField window];
}

/* The primitive for finding; this ends up setting the status field (and beeping if necessary)...
*/
- (BOOL)find:(BOOL)direction {
    unsigned options;
    NSTextView *text = [self textObjectToSearchIn];
    lastFindWasSuccessful = NO;
    if (text) {
        NSString *textContents = [text string];
        unsigned textLength;
        if (textContents && (textLength = [textContents length])) {
            NSRange range;
            BOOL regexSrch;
            BOOL mlflag;
            
            if([regexButton state]) 
            {
                regexSrch = YES;
                if([multilineButton state]) mlflag = YES;
                else mlflag = NO;
            }
            else 
            {
                regexSrch = NO; mlflag = NO;
            }
            options = 0;
            if (direction == Backward) options |= NSBackwardsSearch;
            if ([ignoreCaseButton state]) options |= NSCaseInsensitiveSearch;
            range = [textContents findString:[self findString] selectedRange:[text selectedRange] options:options wrap:YES regex: regexSrch multiline: mlflag];
            if (range.length) {
                [text setSelectedRange:range];
                [text scrollRangeToVisible:range];
                lastFindWasSuccessful = YES;
            }
        
        }
    }
    if (!lastFindWasSuccessful) {
        NSBeep();
        [statusField setStringValue:NSLocalizedStringFromTable(@"Not found", @"FindPanel", @"Status displayed in find panel when the find string is not found.")];
    } else {
        [statusField setStringValue:@""];
    }
    return lastFindWasSuccessful;
}

- (void)orderFrontFindPanel:(id)sender {
    NSPanel *panel = [self findPanel];
    [findTextField selectText:nil];
    [panel makeKeyAndOrderFront:nil];
}

/**** Action methods for gadgets in the find panel; these should all end up setting or clearing the status field ****/

-(IBAction) setRegexState: (id) Sender
{
    //turn off prev
    if([regexButton state])
    {
        [findPrevButton setEnabled: NO];
        [multilineButton setEnabled: YES];
    }
    else
    {
        [findPrevButton setEnabled: YES];
        [multilineButton setEnabled: NO];
    }
    
}


- (void)findNextAndOrderFindPanelOut:(id)sender {
    [findNextButton performClick:nil];
    if (lastFindWasSuccessful) {
        [[self findPanel] orderOut:sender];
    } else {
	[findTextField selectText:nil];
    }
}

- (void)findNext:(id)sender {
    if (findTextField) [self setFindString:[self getFindString]];	/* findTextField should be set */
    (void)[self find:Forward];
}

- (void)findPrevious:(id)sender {
    if (findTextField) [self setFindString:[self getFindString]];	/* findTextField should be set */
    (void)[self find:Backward];
}

- (void)replace:(id)sender 
{
    NSTextView *text = [self textObjectToSearchIn];
    AGRegex *regex;
    
    // shouldChangeTextInRange:... should return NO if !isEditable, but doesn't...
    
    if (text && [text isEditable] && [text shouldChangeTextInRange:[text selectedRange] replacementString:[self getReplaceString]]) 
    {
        int regexOpt;
        
        if([regexButton state])
        {
            NSString *ss;
            regexOpt = 0;
            regexOpt |= ([ignoreCaseButton state])? AGRegexCaseInsensitive : 0;
            regexOpt |= ([multilineButton state])? AGRegexMultiline : 0;
            
            regex = [[AGRegex alloc] initWithPattern: [self findString] options: regexOpt];
            ss = [regex replaceWithStringWithEscape: [replaceTextField stringValue]
                inString: [[text string] substringWithRange: [text selectedRange]]];
            if(!ss) NSBeep();
            else
                [[text textStorage] replaceCharactersInRange:[text selectedRange] withString: ss];
            [regex release];
            [text didChangeText];
    
            
        }
        else
        {
            [[text textStorage] replaceCharactersInRange:[text selectedRange] withString:[self getReplaceString]];
            [text didChangeText];
        }
    }
     else 
    {
        NSBeep();
    }
    [statusField setStringValue:@""];
}

- (void)replaceAndFind:(id)sender {
    [self replace:sender];
    [self findNext:sender];
}

#define ReplaceAllScopeEntireFile 42
#define ReplaceAllScopeSelection 43

/* The replaceAll: code is somewhat complex.  One reason for this is to support undo well --- To play along with the undo mechanism in the text object, this method goes through the shouldChangeTextInRange:replacementString: mechanism. In order to do that, it precomputes the section of the string that is being updated. An alternative would be for this method to handle the undo for the replaceAll: operation itself, and register the appropriate changes. However, this is simpler...

Turns out this approach of building the new string and inserting it at the appropriate place in the actual text storage also has an added benefit of performance; it avoids copying the contents of the string around on every replace, which is significant in large files with many replacements. Of course there is the added cost of the temporary replacement string, but we try to compute that as tightly as possible beforehand to reduce the memory requirements.
*/
- (void)replaceAll:(id)sender {
    NSTextView *text = [self textObjectToSearchIn];
    if (!text || ![text isEditable]) {
	[statusField setStringValue:@""];
        NSBeep();
    } 
    else if([regexButton state])
    {
        NSArray *foundStrings;
        AGRegex *reg;
        AGRegexMatch *match;
        NSString *regResult;
        NSMutableString *cntResult;
        int regexOpt,  n;
        NSRange tr, br;
        NSTextStorage *textStorage = [text textStorage];

        BOOL entireFile = replaceAllScopeMatrix ? ([replaceAllScopeMatrix selectedTag] == ReplaceAllScopeEntireFile) : YES;
         
        /*
            Our strategy is different than the non regex
            We will do an array of found strings and then 
            work our way backwards through it and pay the cost;
            without a find backwards we cannot simply modify the alorithm
            
        */
            regexOpt = 0;
            regexOpt |= ([ignoreCaseButton state])? AGRegexCaseInsensitive : 0;
            regexOpt |= ([multilineButton state])? AGRegexMultiline : 0;
        tr = (entireFile )? NSMakeRange(0, [textStorage length]) : [text selectedRange];
#ifdef newReplaceREGEX
        ans = [reg replaceWithStringWithEscape: [replaceTextField stringValue] inString:  [text string] limit: 0 range: tr];
        [text insertText: ans];
#endif
#ifdef oldReplaceREGEX
        reg = [[AGRegex alloc] initWithPattern: [findTextField stringValue] options: regexOpt];
        foundStrings = [reg findAllInString: [text string] range: tr];
        br = [text selectedRange];
        if((n = [foundStrings count]) > 0)
        {
            //count down so that we're substituting the last first
            //otherwise range will be off
            for(i = n - 1; i>= 0; i--)
            {
                [statusField setStringValue: [NSString stringWithFormat: @"%d/%d", n - i, n]];
                match = [foundStrings objectAtIndex: i];
                regResult = [reg replaceWithStringWithEscape: [replaceTextField stringValue]
                    inString: [[text string] substringWithRange: 
                    [match rangeAtIndex: 0]]];
                /*
                 [[text textStorage] replaceCharactersInRange:
                    [match rangeAtIndex: 0] withString: regResult];
                */
        
                [text setSelectedRange: [match rangeAtIndex: 0]];
                cntResult = [NSMutableString stringWithString: regResult];
                [cntResult replaceOccurrencesOfString: COUNTSTRING withString:
                    [NSString stringWithFormat: @"%d", i+1]
                    options: 0 range: NSMakeRange(0, [cntResult length])];
                [text insertText: cntResult];
            }
            [text didChangeText];
            [text setSelectedRange: br];
            [reg release];
            [statusField setStringValue:[NSString
                localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced",
                 @"FindPanel",
                  @"Status displayed in find panel when indicated number of matches are replaced."), 
                  n]];
        
        }
        else
        {
                [statusField setStringValue:@""];
                NSBeep();       
        }
#endif        
#define realRegexReplaceCode
#ifdef oneAtATimeReplaceRegex
        {
            NSRange range, er;
            BOOL regexSrch;
            NSString *textContents = [text string];
            BOOL mlflag;
            unsigned textLength;
            NSAutoreleasePool *ap;
            unsigned options;
            BOOL direction = Forward;
            NSString *ss;
            unsigned long lastOne;
            textLength = [textContents length];
            er = tr;
            if(!(textContents && textLength)) return;
            tr = (entireFile )? NSMakeRange(0, 0) : [text selectedRange];
            [[text textStorage] beginEditing];
            ap = [[NSAutoreleasePool alloc] init];
            reg = [[AGRegex alloc] initWithPattern: [findTextField stringValue] options: regexOpt];
            br = [text selectedRange];
            //get the whole range
            //go forever
            n = 0;
            lastOne = 0;
            if([regexButton state]) 
            {
                regexSrch = YES;
                if([multilineButton state]) mlflag = YES;
                else mlflag = NO;
            }
            options = 0;
            if (direction == Backward) options |= NSBackwardsSearch;
            if ([ignoreCaseButton state]) options |= AGRegexCaseInsensitive;
            for(;;)
            {
                //find it in the range
                
                range = [textContents findString:[self findString] selectedRange:tr options:options wrap:NO regex: regexSrch multiline: mlflag];
                
                if (range.location == NSNotFound) //here's the great escape
                    break;
                if(NSEqualRanges(er,NSUnionRange(er, range)) == NO) break; //are we out of range?
                
                
                ss = [reg replaceWithStringWithEscape: [replaceTextField stringValue]
                                               inString: [[text string] substringWithRange: range]];
                
                //ss = [NSString string];
                if(range.location <= lastOne) break;
                else lastOne = range.location;
                tr.length = 0;
                tr.location = range.location+range.length + (range.length - [ss length]);
               n++;
                if(!ss) NSBeep();
                else
                    [[text textStorage] replaceCharactersInRange: range withString: ss];
                //[statusField setStringValue: [NSString stringWithFormat: @"%d replaced", n]];
                /*
                [statusField setStringValue:[NSString
                localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced",
                                                                     @"FindPanel",
                                                                     @"Status displayed in find panel when indicated number of matches are replaced."), 
                    
                    n]];*/
                if(n%20 == 0) 
                {
                    [ap release];
                    ap = [[NSAutoreleasePool alloc] init];
                }
            }
            [[text textStorage] endEditing];
            [text didChangeText];
            //make the replace string
            //replace it
            //have we done 20?
            //get re do it;
            
            [text setSelectedRange: br];
            [reg release];
            [ap release];
            [statusField setStringValue:[NSString
                localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced",
                                                                    @"FindPanel",
                                                                    @"Status displayed in find panel when indicated number of matches are replaced"), 
                n]];
                
        }
#endif
#ifdef newestReplaceRegex
        {
            NSTextStorage *textStorage = [text textStorage];
            NSString *textContents = [text string];
            BOOL entireFile = replaceAllScopeMatrix ? ([replaceAllScopeMatrix selectedTag] == ReplaceAllScopeEntireFile) : YES;
            NSRange replaceRange = entireFile ? NSMakeRange(0, [textStorage length]) : [text selectedRange];
            unsigned searchOption = ([ignoreCaseButton state] ? NSCaseInsensitiveSearch : 0);
            unsigned replaced = 0;
            NSRange firstOccurence;
            
            if (findTextField) [self setFindString: [findTextString stringValue]];
    
            // Find the first occurence of the string being replaced; if not found, we're done!
            //need to do this with regex
            match = [regex findInString: textContents range: replaceRange];
            if([match count]) 
            {
                firstOccurence = [match rangeAtIndex: 0];
            }

            
            
            if (firstOccurence.length > 0) {
                NSAutoreleasePool *pool;
                NSString *targetString = [self findString];
                NSString *replaceString = [self getReplaceString];
                [replaceString retain];
                NSMutableAttributedString *temp;	/* This is the temporary work string in which we will do the replacements... */
                NSRange rangeInOriginalString;	/* Range in the original string where we do the searches */
    
                // Find the last occurence of the string and union it with the first occurence to compute the tightest range...
            //--change this
            
            //need to figure out the target string by using regex
            
                rangeInOriginalString = replaceRange = NSUnionRange(firstOccurence, [textContents rangeOfString:targetString options:NSBackwardsSearch|searchOption range:replaceRange]);
    
                temp = [[NSMutableAttributedString alloc] init];
    
                [temp beginEditing];
    
                // The following loop can execute an unlimited number of times, and it could have autorelease activity.
                // To keep things under control, we use a pool, but to be a bit efficient, instead of emptying everytime through
                // the loop, we do it every so often. We can only do this as long as autoreleased items are not supposed to
                // survive between the invocations of the pool!
    
                pool = [[NSAutoreleasePool alloc] init];
    
                while (rangeInOriginalString.length > 0) {
                
                //-- change me
                    NSRange foundRange = [textContents rangeOfString:targetString options:searchOption range:rangeInOriginalString];
                    if (foundRange.length == 0) {
                    
                    //--change me
                        [temp appendAttributedString:[textStorage attributedSubstringFromRange:rangeInOriginalString]];	// Copy the remainder
                        rangeInOriginalString.length = 0;	// And signal that we're done
                    } else {
                        NSRange rangeToCopy = NSMakeRange(rangeInOriginalString.location, foundRange.location - rangeInOriginalString.location + 1);	// Copy upto the start of the found range plus one char (to maintain attributes with the overlap)...
                        [temp appendAttributedString:[textStorage attributedSubstringFromRange:rangeToCopy]];
                        
                        //-- change me
                        [temp replaceCharactersInRange:NSMakeRange([temp length] - 1, 1) withString:replaceString];
                        rangeInOriginalString.length -= NSMaxRange(foundRange) - rangeInOriginalString.location;
                        rangeInOriginalString.location = NSMaxRange(foundRange);
                        replaced++;
                        if (replaced % 100 == 0) {	// Refresh the pool... See warning above!
                            [pool release];
                            pool = [[NSAutoreleasePool alloc] init];
                        }
                    }
                }
    
                [pool release];
                [replaceString autorelease];
                [temp endEditing];
    
                // Now modify the original string
                if ([text shouldChangeTextInRange:replaceRange replacementString:[temp string]]) {
                    [textStorage replaceCharactersInRange:replaceRange withAttributedString:temp];
                    [text didChangeText];
                } else {	// For some reason the string didn't want to be modified. Bizarre...
                    replaced = 0;
                }
    
                [temp release];
            }
            if (replaced == 0) {
                NSBeep();
                [statusField setStringValue:NSLocalizedStringFromTable(@"Not found", @"FindPanel", @"Status displayed in find panel when the find string is not found.")];
            } else {
                [statusField setStringValue:[NSString localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced", @"FindPanel", @"Status displayed in find panel when indicated number of matches are replaced."), replaced]];
            }
        }

#endif 
    }
    else 
    
    {
        NSTextStorage *textStorage = [text textStorage];
        NSString *textContents = [text string];
        BOOL entireFile = replaceAllScopeMatrix ? ([replaceAllScopeMatrix selectedTag] == ReplaceAllScopeEntireFile) : YES;
        NSRange replaceRange = entireFile ? NSMakeRange(0, [textStorage length]) : [text selectedRange];
        unsigned searchOption = ([ignoreCaseButton state] ? NSCaseInsensitiveSearch : 0);
        unsigned replaced = 0;
        NSRange firstOccurence;
        
        if (findTextField) [self setFindString:[self getFindString]];

        // Find the first occurence of the string being replaced; if not found, we're done!
        firstOccurence = [textContents rangeOfString:[self findString] options:searchOption range:replaceRange];
        if (firstOccurence.length > 0) {
	    NSAutoreleasePool *pool;
	    NSString *targetString = [self findString];
	    NSString *replaceString = [self getReplaceString];
             NSMutableAttributedString *temp;	/* This is the temporary work string in which we will do the replacements... */
            NSRange rangeInOriginalString;	/* Range in the original string where we do the searches */
           [replaceString retain];

	    // Find the last occurence of the string and union it with the first occurence to compute the tightest range...
            rangeInOriginalString = replaceRange = NSUnionRange(firstOccurence, [textContents rangeOfString:targetString options:NSBackwardsSearch|searchOption range:replaceRange]);

            temp = [[NSMutableAttributedString alloc] init];

            [temp beginEditing];

	    // The following loop can execute an unlimited number of times, and it could have autorelease activity.
	    // To keep things under control, we use a pool, but to be a bit efficient, instead of emptying everytime through
	    // the loop, we do it every so often. We can only do this as long as autoreleased items are not supposed to
	    // survive between the invocations of the pool!

    	    pool = [[NSAutoreleasePool alloc] init];

            while (rangeInOriginalString.length > 0) {
                NSRange foundRange = [textContents rangeOfString:targetString options:searchOption range:rangeInOriginalString];
                if (foundRange.length == 0) {
                    [temp appendAttributedString:[textStorage attributedSubstringFromRange:rangeInOriginalString]];	// Copy the remainder
                    rangeInOriginalString.length = 0;	// And signal that we're done
                } else {
                    NSRange rangeToCopy = NSMakeRange(rangeInOriginalString.location, foundRange.location - rangeInOriginalString.location + 1);	// Copy upto the start of the found range plus one char (to maintain attributes with the overlap)...
                    [temp appendAttributedString:[textStorage attributedSubstringFromRange:rangeToCopy]];
                    [temp replaceCharactersInRange:NSMakeRange([temp length] - 1, 1) withString:replaceString];
                    rangeInOriginalString.length -= NSMaxRange(foundRange) - rangeInOriginalString.location;
                    rangeInOriginalString.location = NSMaxRange(foundRange);
                    replaced++;
                    if (replaced % 100 == 0) {	// Refresh the pool... See warning above!
                        [pool release];
                        pool = [[NSAutoreleasePool alloc] init];
                    }
                }
            }

	    [pool release];
            [replaceString autorelease];
            [temp endEditing];

	    // Now modify the original string
            if ([text shouldChangeTextInRange:replaceRange replacementString:[temp string]]) {
                [textStorage replaceCharactersInRange:replaceRange withAttributedString:temp];
                [text didChangeText];
            } else {	// For some reason the string didn't want to be modified. Bizarre...
                replaced = 0;
            }

            [temp release];
        }
        if (replaced == 0) {
            NSBeep();
            [statusField setStringValue:NSLocalizedStringFromTable(@"Not found", @"FindPanel", @"Status displayed in find panel when the find string is not found.")];
        } else {
            [statusField setStringValue:[NSString localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced", @"FindPanel", @"Status displayed in find panel when indicated number of matches are replaced."), replaced]];
        }
    }
}

- (void)takeFindStringFromSelection:(id)sender {
    NSTextView *textView = [self textObjectToSearchIn];
    if (textView) {
        NSString *selection = [[textView string] substringWithRange:[textView selectedRange]];
        [self setFindString:selection];
    }
}

- (void) jumpToSelection:sender {
    NSTextView *textView = [self textObjectToSearchIn];
    if (textView) {
        [textView scrollRangeToVisible:[textView selectedRange]];
    }
}

@end


@implementation NSString (NSStringTextFinding)

- (NSRange)findString:(NSString *)string selectedRange:(NSRange)selectedRange options:(unsigned)options wrap:(BOOL)wrap regex: (BOOL) regexFlag multiline: (BOOL) mlFlag {
    BOOL forwards = (options & NSBackwardsSearch) == 0;
    unsigned length = [self length];
    NSRange searchRange, range;

    if (forwards) {
	searchRange.location = NSMaxRange(selectedRange);
	searchRange.length = length - searchRange.location;
        if(regexFlag == YES)
        {
            AGRegex *regex;
            int regexOptions;
            AGRegexMatch *match;
            regexOptions = 0;
            if (options & NSCaseInsensitiveSearch) 
                regexOptions |= AGRegexCaseInsensitive;
            if(mlFlag == YES) regexOptions |= AGRegexMultiline;
            regex = [[AGRegex alloc] initWithPattern: string options: regexOptions];
            match = [regex findInString: self range: searchRange];
            if([match count]) 
            {
                range = [match rangeAtIndex: 0];
            }
            else if(wrap)
            {
                searchRange.location = 0;
                searchRange.length = selectedRange.location;
                match = [regex findInString: self range: searchRange];
                if([match count])
                {
                    range = [match rangeAtIndex: 0];
                }
                else
                {
                    range.length = 0;
                    range.location = NSNotFound;
                }
            }
            else
            {
                range.length = 0;
                range.location = NSNotFound;
            }
            
            [regex release];
            
                
        }
        else
        {
            range = [self rangeOfString:string options:options range:searchRange];
            if ((range.length == 0) && wrap) {	/* If not found look at the first part of the string */
                searchRange.location = 0;
                searchRange.length = selectedRange.location;
                range = [self rangeOfString:string options:options range:searchRange];
            }
        }
    } 
    else 
    {
	searchRange.location = 0;
	searchRange.length = selectedRange.location;
        range = [self rangeOfString:string options:options range:searchRange];
        if ((range.length == 0) && wrap) 
        {
            searchRange.location = NSMaxRange(selectedRange);
            searchRange.length = length - searchRange.location;
            range = [self rangeOfString:string options:options range:searchRange];
        }
    }
    return range;
}        

@end

@implementation AGRegex (NSEscapeReplace)
- (NSString *)replaceWithString:(NSString *)rep inString:(NSString *)str limit:(int)lim range: (NSRange) r
{
    [self replaceWithString: rep inString: [str substringWithRange: r] limit: lim];
}
- (NSString *)replaceWithStringWithEscape:(NSString *)rep inString:(NSString *)str limit: (int) lim range: (NSRange) r
{
    int n, i;
    char ch, chn;
    NSRange rrr;
    NSMutableString *newString = [[NSMutableString alloc] init];
    //go through the replace string
    n = [rep length];
    rrr.location = 0;
    rrr.length = 0;
    for(i = 0; i < n; i++)
    {
        ch = [rep characterAtIndex: i];
        if(ch == '\\' && i < n - 1)
        {
            if(rrr.length)
            {
                [newString appendString: [rep substringWithRange: rrr]];
            }
           chn = [rep characterAtIndex: ++i];
            rrr.length = 0;
           rrr.location = 1+i;
           switch(chn)
            {
                case 't':
                    [newString ADDCHAR('\t')];
                    break;
                case 'n':
                    [newString ADDCHAR('\n')];
                    break;
                case 'r':
                    [newString ADDCHAR('\r')];
                    break;
                default:
                    [newString ADDCHAR('\\')];
                    [newString ADDCHAR(chn)];
                    break;
            }
        }
        else
        {
            rrr.length +=1;
            //[newString ADDCHAR( ch)];
        }
        
    }
    if(rrr.length && rrr.location < n)
    {
        [newString appendString: [rep substringWithRange: rrr]];
    }
    [newString autorelease];
    return [self replaceWithString: newString inString: str limit: lim range: r] ;
                

}
- (NSString *)replaceWithStringWithEscape:(NSString *)rep inString:(NSString *)str  
{
    int n, i;
    char ch, chn;
    NSRange rrr;
    NSMutableString *newString = [[NSMutableString alloc] init];
    //go through the replace string
    n = [rep length];
    rrr.location = rrr.length = 0;
    for(i = 0; i < n; i++)
    {
        ch = [rep characterAtIndex: i];
        if(ch == '\\' && i < n - 1)
        {
            if(rrr.length)
            {
                [newString appendString: [rep substringWithRange: rrr]];
            }
            chn = [rep characterAtIndex: ++i];
            rrr.length = 0;
            rrr.location = i+1;
            switch(chn)
            {
                case 't':
                    [newString ADDCHAR('\t')];
                    break;
                case 'n':
                    [newString ADDCHAR('\n')];
                    break;
                case 'r':
                    [newString ADDCHAR('\r')];
                    break;
                default:
                    [newString ADDCHAR('\\')];
                    [newString ADDCHAR(chn)];
                    break;
            }
        }
        else
        {
            rrr.length +=1;
            //[newString ADDCHAR( ch)];
        }
    }
    if(rrr.length && rrr.location < n)
    {
        [newString appendString: [rep substringWithRange: rrr]];
    }
    [newString autorelease];
    return [self replaceWithString: newString inString: str] ;
                

}
/*
- (NSArray *)findAllInString:(NSString *)str range:(NSRange)range {
	int length = range.length;
        int location = range.location;
	AGRegexMatch *match;
	NSMutableArray *result = [NSMutableArray array];
	NSRange matchRange;
	while (match = [self findInString:str range:range]) {
		[result addObject:match];
		matchRange = [match range];
		range.location = matchRange.location + matchRange.length;
		if (!matchRange.length)
			range.location++;
		range.length = location + length - range.location;
		if (range.location > length)
			break;
	}
	return result;
}
*/
@end