NSTextView中的Xcode样式占位符

Pau*_*son 5 xcode cocoa nstextview

在Xcode中,如果您<# Hello, Word #>在文本编辑器中键入内容,它会自动转换为淡蓝色的药丸形占位符,但在磁盘上,文本仍然与输入的内容完全相同.有谁知道使用相同的效果是否可以实现NSTextView?我有一些非常丑陋的文件路径,必须保持原样,因此sphinx可以将我的文档组合在一起,但我想在用户在我的自定义文本编辑器中查看文件时为其提供一些更具吸引力的东西.

// This on disk (and in any other text editor)
.. image:: images/ssafs/sdfd-sdfsdg-ewfsdf.png

// This shown to the user in my custom text editor
Image of a golden eagle
Run Code Online (Sandbox Code Playgroud)

moh*_*acs 5

尽可能尝试将解释写为代码中的注释。我在这里做了什么。

  1. 使用正则表达式找到所有匹配的链接.. image:: images/ssafs/sdfd-sdfsdg-ewfsdf1.png并将它们添加到数组中。
  2. 将所有匹配的链接替换.. image:: images/ssafs/sdfd-sdfsdg-ewfsdf1.png[Image]字符串
  3. 找到所有 [Image] 字符串并使用 NSMutableAttributedString 作为链接进行格式化。

它会执行您所要求的操作,并且会即时执行,数据库/文件中的源代码根本不会改变。

。H

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSTextViewDelegate>
@property (unsafe_unretained) IBOutlet NSTextView *aTextView;
Run Code Online (Sandbox Code Playgroud)

.米

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    
    //Your NSTextView
    [aTextView setDelegate:(id)self];
    
    // The Context
    NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf1.png lacinia diam, in mattis quam egestas in. Nam gravida dolor adipiscing velit faucibus, vulputate facilisis diam facilisis. Duis id magna nibh. Proin sed turpis aliquet .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf2.png, posuere purus eget, condimentum nulla. Aenean erat odio, suscipit eu aliquet eget, porta in justo. Quisque sed sem dignissim, luctus .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf3.png libero ut, congue libero. Curabitur tristique fermentum risus in fermentum.";
    
    //Regex to find your links .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf2.png
    //You can / should improve Reges patter.
    NSRegularExpression *regexPatternForFullLinks = [NSRegularExpression regularExpressionWithPattern:@"(\\.\\.\\s(.*?\\.png))"
                                                                                              options:NSRegularExpressionCaseInsensitive error:nil];
    //Here find all image links and add them into an Array
    NSArray *arrayOfAllMatches = [regexPatternForFullLinks matchesInString:string options:0 range:NSMakeRange(0, string.length)];
    NSMutableArray *links = [[NSMutableArray alloc] init];
    for (NSTextCheckingResult *match in arrayOfAllMatches) {
        [links addObject:[[string substringWithRange:match.range] stringByReplacingOccurrencesOfString:@".. image:: " withString:@"/"]];
    }

    //Replacing All your links with string: [Image]
    NSString *modifiedString = [regexPatternForFullLinks stringByReplacingMatchesInString:string
                                                                                  options:0
                                                                                    range:NSMakeRange(0, [string length])
                                                                             withTemplate:@"[Image]"];
    
    NSRegularExpression *regexPatternReplaceLinksWithIMAGEStr = [NSRegularExpression regularExpressionWithPattern:@"\\[image\\]"
                                                                                              options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:modifiedString];
    
    //Here,looking for all [Image] strings and add them Link Attribute
    NSArray *arrayOfAllMatchesImageText = [regexPatternReplaceLinksWithIMAGEStr matchesInString:modifiedString
                                                                                        options:0
                                                                                          range:NSMakeRange(0, modifiedString.length)];
   
    for (int i = 0; i < arrayOfAllMatchesImageText.count; i++) {
        NSTextCheckingResult *checkingResult = [arrayOfAllMatchesImageText objectAtIndex:i];
        [attrString beginEditing];
        [attrString addAttribute:NSLinkAttributeName value:[links objectAtIndex:i] range:checkingResult.range];
        [attrString addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:checkingResult.range];
        [attrString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:0] range:checkingResult.range];
        [attrString endEditing];
    }
    
    //Set NSTextView Storage text...
    [aTextView.textStorage setAttributedString:attrString];
}
Run Code Online (Sandbox Code Playgroud)

NSTextViewDelegate:clickedOnLink 处理链接点击。

//Open Given Links with Preview App - NSTextViewDelegate 
- (BOOL)textView:(NSTextView *)aTextView clickedOnLink:(id)link atIndex:(NSUInteger)charIndex {
    [[NSWorkspace sharedWorkspace] openFile:link withApplication:@"Preview"];
    NSLog(@"%@", link);
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

您可以在图像上看到最终结果。如果您愿意,您也可以为链接提供背景颜色。

在此输入图像描述

NSTextView 设置也很重要。

在此输入图像描述

更新:

只要弄清楚这可以更优雅地完成并且效率更高(更快)。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    //Your NSTextView
    [aTextView setDelegate:(id)self];
    
    // The Context
    NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf1.png lacinia diam, in mattis quam egestas in. Nam gravida dolor adipiscing velit faucibus, vulputate facilisis diam facilisis. Duis id magna nibh. Proin sed turpis aliquet .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf2.png, posuere purus eget, condimentum nulla. Aenean erat odio, suscipit eu aliquet eget, porta in justo. Quisque sed sem dignissim, luctus .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf3.png libero ut, congue libero. Curabitur tristique fermentum risus in fermentum.";
    
    //Regex to find your links .. image:: images/ssafs/sdfd-sdfsdg-ewfsdf2.png
    //You can / should improve Reges patter.
    NSRegularExpression *regexPatternForFullLinks = [NSRegularExpression regularExpressionWithPattern:@"(\\.\\.\\s(.*?\\.png))"
                                                                                              options:NSRegularExpressionCaseInsensitive error:nil];
    //Here find all image links and add them into an Array
    NSArray *arrayOfAllMatches = [regexPatternForFullLinks matchesInString:string options:0 range:NSMakeRange(0, string.length)];
    
    __block NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:string];

    [arrayOfAllMatches enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSTextCheckingResult *match = [arrayOfAllMatches objectAtIndex:idx];
        NSString *linkValue = [[string substringWithRange:match.range] stringByReplacingOccurrencesOfString:@".. image:: " withString:@"/"];
        NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [NSColor greenColor],
                                         NSUnderlineStyleAttributeName: [NSNumber numberWithInt:0],
                                         NSLinkAttributeName:linkValue};
        
        NSMutableAttributedString *tempAttrString = [[NSMutableAttributedString alloc] initWithString:@"[Image]" attributes:linkAttributes];
        [attrString beginEditing];
        [attrString replaceCharactersInRange:match.range withAttributedString:tempAttrString];
        [attrString endEditing];
    }];
    [aTextView.textStorage setAttributedString:attrString];
}
Run Code Online (Sandbox Code Playgroud)