aboutsummaryrefslogtreecommitdiff
path: root/XcodePlugin/GTMXcodeCorrectWhiteSpace.m
blob: 51e03e84021f08bfe546757e81db7ecf6407f2cb (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
//
//  GTMXcodeCorrectWhiteSpace.m
//
//  Copyright 2009 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import <Cocoa/Cocoa.h>
#import "GTMObjC2Runtime.h"
#import "GTMXcodePlugin.h"
#import "GTMXcodePreferences.h"

@interface GTMXcodeCorrectWhiteSpace : NSObject
- (BOOL)gdt_writeToFile:(NSString *)fileName ofType:(NSString *)type;
@end

@implementation GTMXcodeCorrectWhiteSpace
// Register our class to perform the swizzle once the plugin has finished
// loading.
+ (void)load {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  [GTMXcodePlugin registerSwizzleClass:self];
  [pool release];
}

// Default initializer. Swizzles [PBXTextFileDocument writeToFile:ofType:]
// with our [gdt_writeToFile:ofType:].
- (id)init {
  if ((self = [super init])) {
    SEL ourSelector = @selector(gdt_writeToFile:ofType:);
    Method ourMethod = class_getInstanceMethod([self class], ourSelector);
    Class pbxClass = NSClassFromString(@"PBXTextFileDocument");
    if (class_addMethod(pbxClass,
                        ourSelector,
                        method_getImplementation(ourMethod),
                        method_getTypeEncoding(ourMethod))) {
      ourMethod = class_getInstanceMethod(pbxClass, ourSelector);
      Method theirMethod
        = class_getInstanceMethod(pbxClass, @selector(writeToFile:ofType:));
      method_exchangeImplementations(ourMethod, theirMethod);
    }
  }
  return self;
}

// Perform a "subtraction of ranges". A - B. Not transitive.
static NSRange SubtractRange(NSRange a, NSRange b) {
  NSRange newRange;
  NSUInteger maxRangeA = NSMaxRange(a);
  NSUInteger maxRangeB = NSMaxRange(b);
  if (b.location == NSNotFound) {
    // B is bogus
    newRange = a;
  } else if (maxRangeB <= a.location) {
    // B is completely before A
    newRange = NSMakeRange(a.location - b.length, a.length);
  } else if (maxRangeA <= b.location) {
    // B is completely after A
    newRange = a;
  } else if (b.location <= a.location && maxRangeB >= maxRangeA) {
    // B subsumes A
    newRange = NSMakeRange(b.location, 0);
  } else if (a.location <= b.location && maxRangeA >= maxRangeB) {
    // A subsumes B
    newRange = NSMakeRange(a.location, a.length - b.length);
  } else if (b.location <= a.location && maxRangeB <= maxRangeA) {
    // B overlaps front edge of A
    NSUInteger diff = maxRangeB - a.location;
    newRange = NSMakeRange(a.location + diff, a.length - diff);
  } else if (b.location <= maxRangeA && maxRangeB >= maxRangeA) {
    // B overlaps back edge of A
    NSUInteger diff = maxRangeA - b.location;
    newRange = NSMakeRange(a.location, a.length - diff);
  }
  return newRange;
}

+ (BOOL)gdt_writeToFile:(NSString *)fileName
                 ofType:(NSString *)type
                 object:(id)object {
  NSTextStorage *storage = [(id)object textStorage];
  id delegate = [storage delegate];

  // Need to keep track of all the current selections so that we can replace
  // them after stripping off the whitespace. A single source file can have
  // multiple views, so we store one selection per view.
  NSArray *windowControllers = [delegate windowControllers];
  size_t size = sizeof(NSRange) * [windowControllers count];
  NSRange *ranges = [[NSMutableData dataWithLength:size] mutableBytes];
  NSUInteger rangeCount = 0;
  for (id controller in windowControllers) {
    if ([controller respondsToSelector:@selector(textView)]) {
      NSTextView *textView = [controller textView];
      ranges[rangeCount] = [textView selectedRange];
      rangeCount++;
    }
  }

  NSMutableString *text = [[[storage string] mutableCopy] autorelease];
  NSRange oldRange = NSMakeRange(0, [text length]);

  // Figure out the newlines in our file.
  NSString *newlineString = @"\n";
  if ([text rangeOfString:@"\r\n"].length > 0) {
    newlineString = @"\r\n";
  } else if ([text rangeOfString:@"\r"].length > 0) {
    newlineString = @"\r";
  }
  NSUInteger newlineStringLength = [newlineString length];
  NSCharacterSet *whiteSpace
    = [NSCharacterSet characterSetWithCharactersInString:@" \t"];
  NSMutableCharacterSet *nonWhiteSpace = [[whiteSpace mutableCopy] autorelease];
  [nonWhiteSpace invert];

  // If the file is missing a newline at the end, add it now.
  if (![text hasSuffix:newlineString]) {
    [text appendString:newlineString];
  }

  NSRange textRange = NSMakeRange(0, [text length] - 1);
  while (textRange.length > 0) {
    NSRange lineRange = [text rangeOfString:newlineString
                                    options:NSBackwardsSearch
                                      range:textRange];
    if (lineRange.location == NSNotFound) {
      lineRange.location = 0;
    } else {
      lineRange.location += newlineStringLength;
    }
    lineRange.length = textRange.length - lineRange.location;
    textRange.length = lineRange.location;
    if (textRange.length != 0) {
      textRange.length -= newlineStringLength;
    }

    NSRange whiteRange = [text rangeOfCharacterFromSet:whiteSpace
                                               options:NSBackwardsSearch
                                                 range:lineRange];
    if (NSMaxRange(whiteRange) == NSMaxRange(lineRange)) {
      NSRange nonWhiteRange = [text rangeOfCharacterFromSet:nonWhiteSpace
                                                    options:NSBackwardsSearch
                                                      range:lineRange];
      NSRange deleteRange;
      if (nonWhiteRange.location == NSNotFound) {
        deleteRange.location = lineRange.location;
      } else {
        deleteRange.location = NSMaxRange(nonWhiteRange);
      }
      deleteRange.length = NSMaxRange(whiteRange) - deleteRange.location;
      [text deleteCharactersInRange:deleteRange];

      // Update all the selections appropriately.
      for (NSUInteger i = 0; i < rangeCount; ++i) {
        NSRange baseRange = ranges[i];
        NSRange newRange = SubtractRange(baseRange, deleteRange);
        ranges[i] = newRange;
      }
    }
  }

  // Replace the text with the new stripped version.
  [storage beginEditing];
  [storage replaceCharactersInRange:oldRange withString:text];
  [storage endEditing];

  // Fix up selections
  NSUInteger count = 0;
  for (id controller in windowControllers) {
    if ([controller respondsToSelector:@selector(textView)]) {
      NSRange newRange = ranges[count];
      if (newRange.location != NSNotFound) {
        NSTextView *textView = [controller textView];
        [textView setSelectedRange:ranges[count]];
      }
      count++;
    }
  }

  // Finish the save.
  return [object gdt_writeToFile:fileName ofType:type];
}

- (BOOL)gdt_writeToFile:(NSString *)fileName ofType:(NSString *)type {
  BOOL isGood;
  // Check our defaults to see if we want to strip whitespace.
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  if ([defaults boolForKey:GTMXcodeCorrectWhiteSpaceOnSave]) {
    isGood = [GTMXcodeCorrectWhiteSpace gdt_writeToFile:fileName
                                                ofType:type
                                                object:self];
  } else {
    isGood = [self gdt_writeToFile:fileName ofType:type];
  }
  return isGood;
}

@end