在NSTextView中显示隐藏字符

7

我正在为Mac OS X编写文本编辑器。 我需要在NSTextView中显示隐藏字符(例如空格,制表符和特殊字符)。 我已经花费了很多时间搜索如何做到这一点,但迄今为止我没有找到答案。如果有人能指点我正确的方向,我将不胜感激。

6个回答

11

这是一个完整可用且干净的实现

@interface GILayoutManager : NSLayoutManager
@end

@implementation GILayoutManager

- (void)drawGlyphsForGlyphRange:(NSRange)range atPoint:(NSPoint)point {
  NSTextStorage* storage = self.textStorage;
  NSString* string = storage.string;
  for (NSUInteger glyphIndex = range.location; glyphIndex < range.location + range.length; glyphIndex++) {
    NSUInteger characterIndex = [self characterIndexForGlyphAtIndex: glyphIndex];
    switch ([string characterAtIndex:characterIndex]) {

      case ' ': {
        NSFont* font = [storage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL];
        [self replaceGlyphAtIndex:glyphIndex withGlyph:[font glyphWithName:@"periodcentered"]];
        break;
      }

      case '\n': {
        NSFont* font = [storage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL];
        [self replaceGlyphAtIndex:glyphIndex withGlyph:[font glyphWithName:@"carriagereturn"]];
        break;
      }

    }
  }

  [super drawGlyphsForGlyphRange:range atPoint:point];
}

@end

安装方式:

[myTextView.textContainer replaceLayoutManager:[[GILayoutManager alloc] init]];

要查找字体图形名称,您需要前往CoreGraphics:

CGFontRef font = CGFontCreateWithFontName(CFSTR("Menlo-Regular"));
for (size_t i = 0; i < CGFontGetNumberOfGlyphs(font); ++i) {
  printf("%s\n", [CFBridgingRelease(CGFontCopyGlyphNameForGlyph(font, i)) UTF8String]);
}

我稍后会发布关于替换已弃用函数的替代功能以及避免连续布局问题的更改。 - uchuugaka
我想补充一点,现在最好使用Core Text来获取字体名称信息。CTFont和相关工具要好得多。 - uchuugaka

5
请查看NSLayoutManager类。您的NSTextView将与一个布局管理器相关联,布局管理器负责将字符(空格、制表符等)与字形(在屏幕上绘制的该字符的图像)关联起来。
在您的情况下,您可能最感兴趣的是replaceGlyphAtIndex:withGlyph:方法,它将允许您替换单个字形。

@Pol发布了更完整的信息,说明由于文档稀少而难以使用的一个困难类别。但两者都有一个限制,即此方法已被弃用,新方法似乎更加困难,因为它使用C数组:D我将添加一些基于此的示例。 - uchuugaka

3

我几年前写了一个文本编辑器 - 这里是一些毫无意义的代码,应该能让你朝着正确的方向看(顺便说一句,这是一个NSLayoutManager子类 - 是的,我知道它像厨房水槽一样漏洞百出):

- (void)drawGlyphsForGlyphRange:(NSRange)glyphRange atPoint:(NSPoint)containerOrigin
{
    if ([[[[MJDocumentController sharedDocumentController] currentDocument] editor] showInvisibles])
    {
        //init glyphs
        unichar crlf = 0x00B6; 
        NSString *CRLF = [[NSString alloc] initWithCharacters:&crlf length:1];
        unichar space = 0x00B7;
        NSString *SPACE = [[NSString alloc] initWithCharacters:&space length:1];
        unichar tab = 0x2192; 
        NSString *TAB = [[NSString alloc] initWithCharacters:&tab length:1];

        NSString *docContents = [[self textStorage] string];
        NSString *glyph;
        NSPoint glyphPoint;
        NSRect glyphRect;
        NSDictionary *attr = [[NSDictionary alloc] initWithObjectsAndKeys:[NSUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"invisiblesColor"]], NSForegroundColorAttributeName, nil];

        //loop thru current range, drawing glyphs
        int i;
        for (i = glyphRange.location; i < NSMaxRange(glyphRange); i++)
        {
            glyph = @"";

            //look for special chars
            switch ([docContents characterAtIndex:i])
            {
                //space
                case ' ':
                    glyph = SPACE;
                    break;

                //tab
                case '\t':
                    glyph = TAB;
                    break;

                //eol
                case 0x2028:
                case 0x2029:
                case '\n':
                case '\r':
                    glyph = CRLF;
                    break;

                //do nothing
                default:
                    glyph = @"";
                    break;                  
            }

            //should we draw?
            if ([glyph length])
            {
                glyphPoint = [self locationForGlyphAtIndex:i];
                glyphRect = [self lineFragmentRectForGlyphAtIndex:i effectiveRange:NULL];
                glyphPoint.x += glyphRect.origin.x;
                glyphPoint.y = glyphRect.origin.y;
                [glyph drawAtPoint:glyphPoint withAttributes:attr];
            }
        }
    }

    [super drawGlyphsForGlyphRange:glyphRange atPoint:containerOrigin];
}

2

以下是Pol在Swift中的解决方案:

class MyLayoutManager: NSLayoutManager {
    override func drawGlyphsForGlyphRange(glyphsToShow: NSRange, atPoint origin: NSPoint) {
        if let storage = self.textStorage {
            let s = storage.string
            let startIndex = s.startIndex
            for var glyphIndex = glyphsToShow.location; glyphIndex < glyphsToShow.location + glyphsToShow.length; glyphIndex++ {
                let characterIndex = self.characterIndexForGlyphAtIndex(glyphIndex)
                let ch = s[startIndex.advancedBy(characterIndex)]
                switch ch {
                case " ":
                    let attrs = storage.attributesAtIndex(characterIndex, effectiveRange: nil)
                    if let font = attrs[NSFontAttributeName] {
                        let g = font.glyphWithName("periodcentered")
                        self.replaceGlyphAtIndex(glyphIndex, withGlyph: g)
                    }
                case "\n":
                    let attrs = storage.attributesAtIndex(characterIndex, effectiveRange: nil)
                    if let font = attrs[NSFontAttributeName] {
//                        let g = font.glyphWithName("carriagereturn")
                        let g = font.glyphWithName("paragraph")
                        self.replaceGlyphAtIndex(glyphIndex, withGlyph: g)
                    }
                case "\t":
                    let attrs = storage.attributesAtIndex(characterIndex, effectiveRange: nil)
                    if let font = attrs[NSFontAttributeName] {
                        let g = font.glyphWithName("arrowdblright")
                        self.replaceGlyphAtIndex(glyphIndex, withGlyph: g)
                    }
                default:
                    break
                }
            }
        }
        super.drawGlyphsForGlyphRange(glyphsToShow, atPoint: origin)
    }
}

列出字形名称:

   func listFonts() {
        let font = CGFontCreateWithFontName("Menlo-Regular")
        for var i:UInt16 = 0; i < UInt16(CGFontGetNumberOfGlyphs(font)); i++ {
            if let name = CGFontCopyGlyphNameForGlyph(font, i) {
                print("name: \(name) at index \(i)")
            }
        }
    }

2
也许-[NSLayoutManager setShowsControlCharacters:]和/或-[NSLayoutManager setShowsInvisibleCharacters:]可以满足您的需求。

2

我解决了在NSTextView中NSGlyphs和相应的unichar之间转换的问题。以下代码运行良好,将空格替换为可见文本的圆点:

- (void)drawGlyphsForGlyphRange:(NSRange)range atPoint:(NSPoint)origin
{
    NSFont *font = [[CURRENT_TEXT_VIEW typingAttributes]
                       objectForKey:NSFontAttributeName];

    NSGlyph bullet = [font glyphWithName:@"bullet"];

    for (int i = range.location; i != range.location + range.length; i++)
    {
        unsigned charIndex = [self characterIndexForGlyphAtIndex:i];

        unichar c =[[[self textStorage] string] characterAtIndex:charIndex];

        if (c == ' ')
            [self replaceGlyphAtIndex:charIndex withGlyph:bullet];
    }

    [super drawGlyphsForGlyphRange:range atPoint:origin];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接