Class

NSTextView

The NSTextView class is the front-end class to the Application Kit’s text system. The class draws the text managed by the back-end components and handles user events to select and modify its text. NSTextView is the principal means to obtain a text object that caters to almost all needs for displaying and managing text at the user interface level. While NSTextView is a subclass of the NSText class—which declares the most general Cocoa interface to the text system—NSTextView adds major features beyond the capabilities of NSText.

Overview

Your applications will use the NSTextView class over the NSText class. It is also important to remember that NSTextView conforms to a large number of protocols as listed above. The methods of these protocols are available to instances of the NSTextView class.

Be sure to read Cocoa Text Architecture Guide and Text System User Interface Layer Programming Guide to fully understand how to use this class.

About Delegate Methods

The NSTextView class communicates with its delegate through methods declared both by the NSTextViewDelegate and by its superclass’s protocol, NSTextDelegate. All delegation messages come from the first text view.

Symbols

Initializing

init(frame: NSRect)

Initializes a text view.

Registering Services Information

class func registerForServices()

Registers send and return types for the Services facility.

Accessing Text System Objects

var textContainer: NSTextContainer?

The receiver’s text container.

func replaceTextContainer(NSTextContainer)

Replaces the text container for the group of text system objects containing the receiver, keeping the association between the receiver and its layout manager intact.

var textContainerInset: NSSize

The empty space the receiver leaves around its associated text container.

var textContainerOrigin: NSPoint

The origin of the receiver’s text container.

func invalidateTextContainerOrigin()

Invalidates the calculated origin of the text container.

var layoutManager: NSLayoutManager?

The layout manager that lays out text for the receiver’s text container.

var textStorage: NSTextStorage?

The receiver’s text storage object.

Setting Graphics Attributes

var backgroundColor: NSColor

The receiver’s background color.

var drawsBackground: Bool

A Boolean value that indicates whether the receiver draws its background.

var allowsDocumentBackgroundColorChange: Bool

A Boolean value that indicates whether the receiver allows its background color to change.

func changeDocumentBackgroundColor(Any?)

An action method used to set the background color.

Controlling Display

func setNeedsDisplay(NSRect, avoidAdditionalLayout: Bool)

Marks the receiver as requiring display.

var shouldDrawInsertionPoint: Bool

A Boolean value that determines whether the receiver should draw its insertion point.

func drawBackground(in: NSRect)

Draws the background of the text view.

func setConstrainedFrameSize(NSSize)

Attempts to set the frame size as if by user action.

func cleanUpAfterDragOperation()

Releases the drag information still existing after the dragging session has completed.

func showFindIndicator(for: NSRange)

Causes a temporary highlighting effect to appear around the visible portion (or portions) of the specified range.

Inserting Text

func insertText(Any)

Inserts aString into the receiver’s text at the insertion point if there is one, otherwise replacing the selection.

Deprecated
var allowedInputSourceLocales: [String]?

An array of locale identifiers representing input sources that are allowed to be enabled when the receiver has the keyboard focus.

Setting Behavioral Attributes

var allowsUndo: Bool

A Boolean value that indicates whether the receiver allows undo.

var isEditable: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager allow the user to edit text.

var isSelectable: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager allow the user to select text.

var isFieldEditor: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager behave as field editors.

var isRichText: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager allow the user to apply attributes to specific ranges of text.

var importsGraphics: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager allow the user to import files by dragging.

func setBaseWritingDirection(NSWritingDirection, range: NSRange)

Sets the base writing direction of a range of text.

var defaultParagraphStyle: NSParagraphStyle?

The receiver’s default paragraph style.

func outline(Any?)

Adds the outline attribute to the selected text attributes if absent; removes the attribute if present.

var allowsImageEditing: Bool

Indicates whether image attachments should permit editing of their images.

var isAutomaticQuoteSubstitutionEnabled: Bool

A Boolean value that enables and disables automatic quotation mark substitution.

func toggleAutomaticQuoteSubstitution(Any?)

Changes the state of automatic quotation mark substitution from enabled to disabled and vice versa.

var isAutomaticLinkDetectionEnabled: Bool

A Boolean value that enables or disables automatic link detection.

func toggleAutomaticLinkDetection(Any?)

Changes the state of automatic link detection from enabled to disabled and vice versa.

var displaysLinkToolTips: Bool

A Boolean value that indicates whether the text view automatically supplies the destination of a link as a tooltip for text that has a link attribute.

Using Text Formatting Controls

var usesRuler: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager use a ruler.

var isRulerVisible: Bool

A Boolean value that controls whether the scroll view enclosing text views sharing the receiver’s layout manager displays the ruler.

var usesInspectorBar: Bool

A Boolean value that indicates whether this text view uses the inspector bar.

Managing the Selection

var selectedRanges: [NSValue]

An array containing the ranges of characters selected in the receiver’s layout manager.

func setSelectedRange(NSRange)

Sets the selection to the characters in an array of ranges.

func setSelectedRange(NSRange, affinity: NSSelectionAffinity, stillSelecting: Bool)

Sets the selection to a range of characters in response to user action.

func setSelectedRanges([NSValue], affinity: NSSelectionAffinity, stillSelecting: Bool)

Sets the selection to the characters in an array of ranges in response to user action.

var selectionAffinity: NSSelectionAffinity

The preferred direction of selection.

var selectionGranularity: NSSelectionGranularity

The selection granularity for subsequent extension of a selection.

var insertionPointColor: NSColor

The color of the insertion point.

func updateInsertionPointStateAndRestartTimer(Bool)

Updates the insertion point’s location and optionally restarts the blinking cursor timer.

var selectedTextAttributes: [String : Any]

The attributes used to indicate the selection.

var markedTextAttributes: [String : Any]?

The attributes used to draw marked text.

var linkTextAttributes: [String : Any]?

The attributes used to draw the onscreen presentation of link text.

func characterIndexForInsertion(at: NSPoint)

Returns a character index appropriate for placing a zero-length selection for an insertion point associated with the mouse at the given point.

Managing the Pasteboard

func preferredPasteboardType(from: [String], restrictedToTypesFrom: [String]?)

Returns whatever type on the pasteboard would be most preferred for copying data.

func readSelection(from: NSPasteboard)

Reads the text view’s preferred type of data from the specified pasteboard.

func readSelection(from: NSPasteboard, type: String)

Reads data of the given type from the specified pasteboard.

var readablePasteboardTypes: [String]

The types this text view can read immediately from the pasteboard.

var writablePasteboardTypes: [String]

The pasteboard types that can be provided from the current selection.

func writeSelection(to: NSPasteboard, type: String)

Writes the current selection to the specified pasteboard using the given type.

func writeSelection(to: NSPasteboard, types: [String])

Writes the current selection to the specified pasteboard under each given type.

func validRequestor(forSendType: String, returnType: String)

Returns self if the text view can provide and accept the specified data types, or nil if it can't.

Setting Text Attributes

func alignJustified(Any?)

Applies full justification to selected paragraphs (or all text, if the receiver is a plain text object).

func changeAttributes(Any?)

Changes the attributes of the current selection.

func changeColor(Any?)

Sets the color of the selected text.

func setAlignment(NSTextAlignment, range: NSRange)

Sets the alignment of the paragraphs containing characters in the specified range.

var typingAttributes: [String : Any]

The receiver’s typing attributes.

func useStandardKerning(Any?)

Set the receiver to use pair kerning data for the glyphs in its selection, or for all glyphs if the receiver is a plain text view.

func lowerBaseline(Any?)

Lowers the baseline offset of selected text by 1 point, or of all text if the receiver is a plain text view.

func raiseBaseline(Any?)

Raises the baseline offset of selected text by 1 point, or of all text if the receiver is a plain text view.

func turnOffKerning(Any?)

Sets the receiver to use nominal glyph spacing for the glyphs in its selection, or for all glyphs if the receiver is a plain text view.

func loosenKerning(Any?)

Increases the space between glyphs in the receiver’s selection, or in all text if the receiver is a plain text view.

func tightenKerning(Any?)

Decreases the space between glyphs in the receiver’s selection, or for all glyphs if the receiver is a plain text view.

func useStandardLigatures(Any?)

Sets the receiver to use the standard ligatures available for the fonts and languages used when setting text, for the glyphs in the selection if the receiver is a rich text view, or for all glyphs if it’s a plain text view.

func turnOffLigatures(Any?)

Sets the receiver to use only required ligatures when setting text, for the glyphs in the selection if the receiver is a rich text view, or for all glyphs if it’s a plain text view.

func useAllLigatures(Any?)

Sets the receiver to use all ligatures available for the fonts and languages used when setting text, for the glyphs in the selection if the receiver is a rich text view, or for all glyphs if it’s a plain text view.

func toggleTraditionalCharacterShape(Any?)

Toggles the NSCharacterShapeAttributeName attribute at the current selection.

Deprecated

Clicking and Pasting

func clicked(onLink: Any, at: Int)

Causes the text view to act as if the user clicked on some text with the given link as the value of a link attribute associated with the text.

func pasteAsPlainText(Any?)

Inserts the contents of the pasteboard into the receiver’s text as plain text.

func pasteAsRichText(Any?)

This action method inserts the contents of the pasteboard into the receiver’s text as rich text, maintaining its attributes.

Undo Support

func breakUndoCoalescing()

Informs the receiver that it should begin coalescing successive typing operations in a new undo grouping.

var isCoalescingUndo: Bool

A Boolean value that indicates whether undo coalescing is in progress.

Methods for Subclasses to Use or Override

func updateFontPanel()

Updates the Font panel to contain the font attributes of the selection.

func updateRuler()

Updates the ruler view in the receiver’s enclosing scroll view to reflect the selection’s paragraph and marker attributes.

var acceptableDragTypes: [String]

The data types that the receiver accepts as the destination view of a dragging operation.

func updateDragTypeRegistration()

Updates the acceptable drag types of all text views associated with the receiver's layout manager.

func selectionRange(forProposedRange: NSRange, granularity: NSSelectionGranularity)

Returns an adjusted selected range based on the selection granularity.

var rangeForUserCharacterAttributeChange: NSRange

The range of characters affected by an action method that changes character (not paragraph) attributes.

var rangesForUserCharacterAttributeChange: [NSValue]?

An array containing the ranges of characters affected by an action method that changes character (not paragraph) attributes.

var rangeForUserParagraphAttributeChange: NSRange

The range of characters affected by an action method that changes paragraph (not character) attributes.

var rangesForUserParagraphAttributeChange: [NSValue]?

An array containing the ranges of characters affected by a method that changes paragraph (not character) attributes.

var rangeForUserTextChange: NSRange

The range of characters affected by a method that changes characters (as opposed to attributes).

var rangesForUserTextChange: [NSValue]?

An array containing the ranges of characters affected by a method that changes characters (as opposed to attributes).

func shouldChangeText(in: NSRange, replacementString: String?)

Initiates a series of delegate messages (and general notifications) to determine whether modifications can be made to the characters and attributes of the receiver’s text.

func shouldChangeText(inRanges: [NSValue], replacementStrings: [String]?)

Initiates a series of delegate messages (and general notifications) to determine whether modifications can be made to the characters and attributes of the receiver’s text.

func didChangeText()

Sends out necessary notifications when a text change completes.

var smartInsertDeleteEnabled: Bool

A Boolean value that controls whether the receiver inserts or deletes space around selected words so as to preserve proper spacing and punctuation.

func smartDeleteRange(forProposedRange: NSRange)

Returns an extended range that includes adjacent whitespace that should be deleted along with the proposed range in order to preserve proper spacing and punctuation.

func smartInsert(afterStringFor: String, replacing: NSRange)

Returns any whitespace that needs to be added after the string to preserve proper spacing and punctuation when the string replaces the characters in the specified range.

func smartInsert(beforeStringFor: String, replacing: NSRange)

Returns any whitespace that needs to be added before the string to preserve proper spacing and punctuation when the string replaces the characters in the specified range.

func smartInsert(for: String, replacing: NSRange, before: AutoreleasingUnsafeMutablePointer<NSString?>?, after: AutoreleasingUnsafeMutablePointer<NSString?>?)

Determines whether whitespace needs to be added around the string to preserve proper spacing and punctuation when it replaces the characters in the specified range.

func toggleSmartInsertDelete(Any?)

Changes the state of smart insert and delete from enabled to disabled and vice versa.

Working With the Spelling Checker

var isContinuousSpellCheckingEnabled: Bool

A Boolean value that indicates whether the receiver has continuous spell checking enabled.

var spellCheckerDocumentTag: Int

A tag identifying the text view's text as a document for the spell checker server.

func toggleContinuousSpellChecking(Any?)

Toggles whether continuous spell checking is enabled for the receiver.

var isGrammarCheckingEnabled: Bool

Enables and disables grammar checking.

func toggleGrammarChecking(Any?)

Changes the state of grammar checking from enabled to disabled and vice versa.

func setSpellingState(Int, range: NSRange)

Sets the spelling state, which controls the display of the spelling and grammar indicators on the given text range.

Working with the Sharing Service Picker

func orderFrontSharingServicePicker(Any?)

Creates and displays a new instance of the the sharing service picker.

NSRulerView Client Methods

func rulerView(NSRulerView, didMove: NSRulerMarker)

Modifies the paragraph style of the paragraphs containing the selection to record the new location of the marker.

func rulerView(NSRulerView, willMove: NSRulerMarker, toLocation: CGFloat)

Returns a potentially modified location to which the marker should be moved.

func rulerView(NSRulerView, shouldMove: NSRulerMarker)

Returns whether the marker should be moved.

func rulerView(NSRulerView, didRemove: NSRulerMarker)

Modifies the paragraph style of the paragraphs containing the selection—if possible—by removing the specified marker.

func rulerView(NSRulerView, shouldRemove: NSRulerMarker)

Returns whether the marker should be removed.

func rulerView(NSRulerView, didAdd: NSRulerMarker)

Modifies the paragraph style of the paragraphs containing the selection to accommodate a new marker.

func rulerView(NSRulerView, shouldAdd: NSRulerMarker)

Returns whether a new marker can be added.

func rulerView(NSRulerView, willAdd: NSRulerMarker, atLocation: CGFloat)

Returns a potentially modified location to which the marker should be added.

func rulerView(NSRulerView, handleMouseDownWith: NSEvent)

Adds a left tab marker to the ruler at the location clicked.

Assigning a Delegate

var delegate: NSTextViewDelegate?

The delegate for all text views sharing the receiver’s layout manager.

Dragging

func dragImageForSelection(with: NSEvent, origin: NSPointPointer?)

Returns an appropriate drag image for the drag initiated by the specified event.

func dragOperation(for: NSDraggingInfo, type: String)

Returns the type of drag operation that should be performed if the image were released now.

func dragSelection(with: NSEvent, offset: NSSize, slideBack: Bool)

Begins dragging the current selected text range.

var acceptsGlyphInfo: Bool

A Boolean value that indicates whether the receiver accepts the glyph info attribute.

Speaking Text

func startSpeaking(Any?)

Speaks the selected text, or all text if no selection.

func stopSpeaking(Any?)

Stops the speaking of text.

Working with Panels

var usesFontPanel: Bool

A Boolean value that controls whether the text views sharing the receiver’s layout manager use the Font panel and Font menu.

var usesFindPanel: Bool

A Boolean value that indicates whether the receiver allows for a find panel.

func performFindPanelAction(Any?)

Performs a find panel action specified by the sender's tag.

func orderFrontLinkPanel(Any?)

Brings forward a panel allowing the user to manipulate links in the text view.

func orderFrontListPanel(Any?)

Brings forward a panel allowing the user to manipulate text lists in the text view.

func orderFrontSpacingPanel(Any?)

Brings forward a panel allowing the user to manipulate text line heights, interline spacing, and paragraph spacing, in the text view.

func orderFrontTablePanel(Any?)

Brings forward a panel allowing the user to manipulate text tables in the text view.

func orderFrontSubstitutionsPanel(Any?)

Brings forward a panel allowing the user to specify string substitutions in the text view.

Text Completion

func complete(Any?)

Invokes completion in a text view.

func completions(forPartialWordRange: NSRange, indexOfSelectedItem: UnsafeMutablePointer<Int>)

Returns an array of potential completions, in the order to be presented, representing possible word completions available from a partial word.

func insertCompletion(String, forPartialWordRange: NSRange, movement: Int, isFinal: Bool)

Inserts the selected completion into the text at the appropriate location.

var rangeForUserCompletion: NSRange

The partial range from the most recent beginning of a word up to the insertion point.

Text Checking and Substitutions

func checkTextInDocument(Any?)

Performs the default text checking on the entire document.

func checkTextInSelection(Any?)

Performs the default text checking on the current selection.

func checkText(in: NSRange, types: NSTextCheckingTypes, options: [String : Any] = [:])

Check and replace the text in the range using the specified checking types and options.

var isAutomaticDashSubstitutionEnabled: Bool

A Boolean value that indicates whether automatic dash substitution is enabled.

func toggleAutomaticDashSubstitution(Any?)

Toggles the state of the automatic dash substitution.

var isAutomaticDataDetectionEnabled: Bool

A Boolean value that indicates whether automatic data detection is enabled.

func toggleAutomaticDataDetection(Any?)

Toggles the state of the automatic data detection.

var isAutomaticSpellingCorrectionEnabled: Bool

A Boolean value that indicates whether automatic spelling correction is enabled.

func toggleAutomaticSpellingCorrection(Any?)

Toggles the state of the automatic spelling correction.

var isAutomaticTextReplacementEnabled: Bool

A Boolean value that indicates whether automatic text replacement is enabled.

func toggleAutomaticTextReplacement(Any?)

Toggles the state of the automatic text replacement.

Supporting QuickLook

func updateQuickLookPreviewPanel()

Notifies the QuickLook panel that an update may be required.

func toggleQuickLookPreviewPanel(Any?)

An action message that toggles the visibility state of the Quick Look preview panel.

Changing Layout Orientation

func changeLayoutOrientation(Any?)

An action method that sets the layout orientation of the text.

func setLayoutOrientation(NSTextLayoutOrientation)

Changes the receiver's layout orientation and invalidates the contents.

Using the Find Bar

var usesFindBar: Bool

A Boolean value that indicates whether to use the find bar for this text view.

var isIncrementalSearchingEnabled: Bool

A Boolean value that indicates whether incremental searching is enabled.

Constants

NSSelectionGranularity

These constants specify how much the text view extends the selection when the user drags the mouse. They’re used by selectionGranularity, and selectionRange(forProposedRange:granularity:):

NSSelectionAffinity

These constants specify the preferred direction of selection. They’re used by selectionAffinity and setSelectedRange(_:affinity:stillSelecting:).

NSFindPanelAction

These constants define the tags for performFindPanelAction(_:).

Input Sources Locale Identifiers

Locale identifiers represent the input sources available.

Find Panel Search Metadata

In addition to communicating search strings via the find pasteboard, the standard Find panel for NSTextView also communicates search option metadata, including case sensitivity and substring matching options. This metadata is stored in a property list as the NSFindPanelSearchOptionsPboardType value on the global find pasteboard. As such, third party applications may store additional keys in this property list to communicate additional metadata as desired to support the various search options common to many third-party applications' Find panels.

NSFindPanelSubstringMatchType

The type of substring matching used by the Find panel.

Notifications

NSTextView posts the following notifications as well as those declared by its superclasses, particularly NSText. See the Notifications section in the NSText class specification for those other notifications.

static let NSTextViewDidChangeSelection: NSNotification.Name

Posted when the selected range of characters changes.

static let NSTextViewWillChangeNotifyingTextView: NSNotification.Name

Posted when a new text view is established as the text view that sends notifications.

static let NSTextViewDidChangeTypingAttributes: NSNotification.Name

Posted when there is a change in the typing attributes within a text view.