nstextview 在粘贴过程中用 space 替换制表符

nstextview replace tabs with space during paste

我有一个子类 NSTextView,我想修改用户输入(基于偏好)以用空格替换制表符。到目前为止,我已经将 insertTab 方法修改为如下所示:

- (void) insertTab: (id) sender
{
    if(shouldInsertSpaces) {
        [self insertText: @"    "];
        return;
    }

    [super insertTab: sender];
}

但我还想在粘贴事件中替换空格。我想到的一种解决方案是修改 NSTextStorage replaceCharacter:with: 方法,但我发现如果我将数据加载到文本视图中,它会替换文本。具体来说,我只想修改用户手动输入的文本。

一个解决方案 found here 建议修改粘贴板,但我不想这样做,因为我不想弄乱用户的粘贴板,如果他们想粘贴到其他地方。有没有人对我如何着手提出任何其他建议?

在另一个问题中提到,请看readSelectionFromPasteboard:type:。覆盖它并替换粘贴板。例如:

- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type {
    id data = [pboard dataForType:type];
    NSDictionary *dictionary = nil;
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithRTF:data documentAttributes:&dictionary];
    for (;;) {
        NSRange range = [[text string] rangeOfString:@"\t"];
        if (range.location == NSNotFound)
            break;
        [text replaceCharactersInRange:range withString:@"    "];
    }
    data = [text RTFFromRange:NSMakeRange(0, text.length) documentAttributes:dictionary];
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:@"MyNoTabsPasteBoard"];
    [pasteboard clearContents];
    [pasteboard declareTypes:@[type] owner:self];
    [pasteboard setData:data forType:type];
    return [super readSelectionFromPasteboard:pasteboard type:type];
}