Skip to content

Commit

Permalink
- 格式化完之后选中Import的行
Browse files Browse the repository at this point in the history
  • Loading branch information
VernonVan committed Feb 2, 2018
1 parent 3995087 commit acd0950
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions ImportArranger/PPImportArrangerCommand.m
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ - (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocati
NSInteger firstLine = -1;
for (NSUInteger index = 0, max = lines.count; index < max; index++) {
NSString *line = lines[index];
NSString *pureLine = [line stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *pureLine = [line stringByReplacingOccurrencesOfString:@" " withString:@""]; // 去掉多余的空格,以防被空格干扰没检测到 #import
// 支持 Objective-C、Swift、C 语言
if ([pureLine hasPrefix:@"#import"] || [pureLine hasPrefix:@"import"] || [pureLine hasPrefix:@"@class"]
|| [pureLine hasPrefix:@"@import"] || [pureLine hasPrefix:@"#include"]) {
[importLines addObject:line];
if (firstLine == -1) {
firstLine = index;
firstLine = index; // 记住第一行 #import 所在的行数,用来等下重新插入的位置
}
}
}
Expand All @@ -39,8 +40,8 @@ - (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocati

[invocation.buffer.lines removeObjectsInArray:importLines];

NSArray *noRepeatArray = [[NSSet setWithArray:importLines] allObjects]; // 去掉重复的 import
NSMutableArray *sortedImports = [[NSMutableArray alloc] initWithArray:[noRepeatArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
NSArray *noRepeatArray = [[NSSet setWithArray:importLines] allObjects]; // 去掉重复的 #import
NSMutableArray<NSString *> *sortedImports = [[NSMutableArray alloc] initWithArray:[noRepeatArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];

// 引用系统文件在前,用户自定义的文件在后
NSMutableArray *systemImports = [[NSMutableArray alloc] init];
Expand All @@ -55,7 +56,10 @@ - (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocati
}

if (firstLine >= 0 && firstLine < invocation.buffer.lines.count) {
// 重新插入排好序的 #import 行
[invocation.buffer.lines insertObjects:sortedImports atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstLine, sortedImports.count)]];
// 选中所有 #import 行
[invocation.buffer.selections addObject:[[XCSourceTextRange alloc] initWithStart:XCSourceTextPositionMake(firstLine, 0) end:XCSourceTextPositionMake(firstLine + sortedImports.count, sortedImports.lastObject.length)]];
}

completionHandler(nil);
Expand Down

0 comments on commit acd0950

Please sign in to comment.