mh taqia mh taqia - 10 months ago 123
Objective-C Question

Programmatically obtain font name of selected text in TextEdit

After trying for two months I find out how to obtain AttributedString from any text range of TextEdit (or any NSTextView). my code is as:

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement,
kAXFocusedUIElementAttribute, (CFTypeRef*)&focussedElement);
if (error != kAXErrorSuccess) {
println("Could not get focussed element");
else {
AXValueRef selectedRangeValue = NULL;
AXError getSelectedRangeError =
kAXSelectedTextRangeAttribute, (CFTypeRef*)&selectedRangeValue);
if (getSelectedRangeError == kAXErrorSuccess) {
CFRange selectedRange;
AXValueGetValue(selectedRangeValue, kAXValueCFRangeType,
AXValueRef attributedString = NULL;
AXError getAttrStrError =
kAXAttributedStringForRangeParameterizedAttribute, selectedRangeValue,

if (getAttrStrError == kAXErrorSuccess)
CFAttributedStringRef attrStr = (CFAttributedStringRef)attributedString;

CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);

println("value: %X", value); // value is not NULL, but I can't obtain font name from it.

println("Could not get attributed string for selected range");
else {
println("Could not get selected range");
if (focussedElement != NULL)

I properly obtained CFAttributedStringRef (I can get length or plain text from it), but I can not obtain font name.


the value returned form below code is not NULL:

CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);

The value can not be assumed as CTFontRef or CGFontRef, ATSFontRef, ... (causes exception).

Also I try kCTFontAttributeName instead kAXFontTextAttribute, but returns NULL.

Thanks a lot.


The value associated with the key kAXFontTextAttribute seems to be a CFDictionaryRef. See AXTextAttributedString documentation.