Get and set current text selection in Features-Tab of Font-Info

How can I get and set the current text selection in the features tab of the font info window by script?

You can use the following code:

app = NSApplication.sharedApplication()
# the key window is the window that is currently active
keyWindow = app.keyWindow()
# the first responder is the control in the window that is currently active
textView = keyWindow.firstResponder()

# check whether the current control has a selected text
if textView.respondsToSelector_('selectedRange'):
	# get the text from text view
	string = textView.string()
	# get the selected range of the text view
	selectedRange = textView.selectedRange()
	# get the selected substring from the total string
	substring = string.substringWithRange_(selectedRange)
	# do something with the selected substring
	print("no text view is currently active")

Setting is a bit more difficult depending on what you are planing to do. Can you describe your use case?

There is a direct way to get to the text view:

textView = Font.parent.windowController().fontInfoWindowController().featureController().featureText()

Florians example does not work here, but Georgs does. Although only in Glyphs 3.

I want to write a script, that comments a whole block of selected text out.

You could just use the Command+/ shortcut to do that (the same as the default in Xcode and TextMate).

And Florians code only works if the feature edit view is active and has key input. So you need to run your script from with a shortcut, not from the macro window.

The benefit of my code is that is works in other text view such as the Macro panel, too. But yes, the text view needs to active.