Display hidden characters in NSTextView

前端 未结 6 1556
孤城傲影
孤城傲影 2020-12-15 01:14

I am writing a text editor for Mac OS X. I need to display hidden characters in an NSTextView (such as spaces, tabs, and special characters). I have spent a lot of time se

6条回答
  •  再見小時候
    2020-12-15 01:47

    Here is Pol's solution in 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)
        }
    }
    

    And to list the glyph names:

       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)")
                }
            }
        }
    

提交回复
热议问题