Class

NSTextView

A view that draws text and handles user interactions with that text.

Declaration

@interface NSTextView : NSText

Overview

The NSTextView class is the front-end class to the AppKit text system. The class draws the text managed by the back-end components and handles user events to select and modify its text, in addition to supporting rich text, attachments, input management and key binding, and marked text attributes.

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. You can also do more powerful and more creative text manipulation (such as displaying text in a circle) using NSTextStorage, NSLayoutManager, NSTextContainer, and related classes.

You are more likely to use the NSTextView class than the NSText class. It is also important to remember that NSTextView conforms to a large number of protocols, the methods of which are available to instances of the NSTextView class.

NSTextView 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. To fully understand how to use this class, read Cocoa Text Architecture Guide and Text System User Interface Layer Programming Guide.

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.

Topics

Initializing

- initWithFrame:textContainer:

Initializes a text view.

- initWithFrame:

Initializes a text view.

Accessing the Delegate

delegate

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

NSTextViewDelegate

A set of optional methods that text view delegates can use to manage selection, set text attributes, work with the spell checker, and more.

Registering Services Information

+ registerForServices

Registers send and return types for the Services facility.

Accessing Text System Objects

textContainer

The receiver’s text container.

- replaceTextContainer:

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.

textContainerInset

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

textContainerOrigin

The origin of the receiver’s text container.

- invalidateTextContainerOrigin

Invalidates the calculated origin of the text container.

layoutManager

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

textStorage

The receiver’s text storage object.

Setting Graphics Attributes

backgroundColor

The receiver’s background color.

drawsBackground

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

allowsDocumentBackgroundColorChange

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

- changeDocumentBackgroundColor:

An action method used to set the background color.

Controlling Display

- setNeedsDisplayInRect:avoidAdditionalLayout:

Marks the receiver as requiring display.

shouldDrawInsertionPoint

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

- drawInsertionPointInRect:color:turnedOn:

Draws or erases the insertion point.

- drawViewBackgroundInRect:

Draws the background of the text view.

- setConstrainedFrameSize:

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

- cleanUpAfterDragOperation

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

- showFindIndicatorForRange:

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

Inserting Text

- insertText:

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

Deprecated
allowedInputSourceLocales

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

Setting Behavioral Attributes

allowsUndo

A Boolean value that indicates whether the receiver allows undo.

editable

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

selectable

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

fieldEditor

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

richText

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.

importsGraphics

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

- setBaseWritingDirection:range:

Sets the base writing direction of a range of text.

- toggleBaseWritingDirection:

Changes the base writing direction of a paragraph between left-to-right and right-to-left.

Deprecated
defaultParagraphStyle

The receiver’s default paragraph style.

- outline:

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

allowsImageEditing

Indicates whether image attachments should permit editing of their images.

automaticQuoteSubstitutionEnabled

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

- toggleAutomaticQuoteSubstitution:

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

automaticLinkDetectionEnabled

A Boolean value that enables or disables automatic link detection.

- toggleAutomaticLinkDetection:

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

displaysLinkToolTips

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

usesRuler

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

rulerVisible

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

usesInspectorBar

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

Managing the Selection

selectedRanges

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

- setSelectedRange:

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

- setSelectedRange:affinity:stillSelecting:

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

- setSelectedRanges:affinity:stillSelecting:

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

selectionAffinity

The preferred direction of selection.

selectionGranularity

The selection granularity for subsequent extension of a selection.

insertionPointColor

The color of the insertion point.

- updateInsertionPointStateAndRestartTimer:

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

selectedTextAttributes

The attributes used to indicate the selection.

markedTextAttributes

The attributes used to draw marked text.

linkTextAttributes

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

- characterIndexForInsertionAtPoint:

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

- preferredPasteboardTypeFromArray:restrictedToTypesFromArray:

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

- readSelectionFromPasteboard:

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

- readSelectionFromPasteboard:type:

Reads data of the given type from the specified pasteboard.

readablePasteboardTypes

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

writablePasteboardTypes

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

- writeSelectionToPasteboard:type:

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

- writeSelectionToPasteboard:types:

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

- validRequestorForSendType:returnType:

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

Setting Text Attributes

- alignJustified:

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

- changeAttributes:

Changes the attributes of the current selection.

- changeColor:

Sets the color of the selected text.

- setAlignment:range:

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

typingAttributes

The receiver’s typing attributes.

- useStandardKerning:

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.

- lowerBaseline:

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

- raiseBaseline:

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

- turnOffKerning:

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.

- loosenKerning:

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

- tightenKerning:

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

- useStandardLigatures:

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.

- turnOffLigatures:

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.

- useAllLigatures:

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.

- toggleTraditionalCharacterShape:

Toggles the NSCharacterShapeAttributeName attribute at the current selection.

Deprecated

Clicking and Pasting

- clickedOnLink:atIndex:

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.

- pasteAsPlainText:

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

- pasteAsRichText:

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

Undo Support

- breakUndoCoalescing

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

coalescingUndo

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

Methods for Subclasses to Use or Override

- updateFontPanel

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

- updateRuler

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

acceptableDragTypes

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

- updateDragTypeRegistration

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

- selectionRangeForProposedRange:granularity:

Returns an adjusted selected range based on the selection granularity.

rangeForUserCharacterAttributeChange

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

rangesForUserCharacterAttributeChange

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

rangeForUserParagraphAttributeChange

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

rangesForUserParagraphAttributeChange

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

rangeForUserTextChange

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

rangesForUserTextChange

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

- shouldChangeTextInRange:replacementString:

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.

- shouldChangeTextInRanges:replacementStrings:

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.

- didChangeText

Sends out necessary notifications when a text change completes.

smartInsertDeleteEnabled

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

- smartDeleteRangeForProposedRange:

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.

- smartInsertAfterStringForString:replacingRange:

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.

- smartInsertBeforeStringForString:replacingRange:

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.

- smartInsertForString:replacingRange:beforeString:afterString:

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.

- toggleSmartInsertDelete:

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

Working With the Spelling Checker

continuousSpellCheckingEnabled

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

spellCheckerDocumentTag

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

- toggleContinuousSpellChecking:

Toggles whether continuous spell checking is enabled for the receiver.

grammarCheckingEnabled

Enables and disables grammar checking.

- toggleGrammarChecking:

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

- setSpellingState:range:

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

- orderFrontSharingServicePicker:

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

NSRulerView Client Methods

- rulerView:didMoveMarker:

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

- rulerView:willMoveMarker:toLocation:

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

- rulerView:shouldMoveMarker:

Returns whether the marker should be moved.

- rulerView:didRemoveMarker:

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

- rulerView:shouldRemoveMarker:

Returns whether the marker should be removed.

- rulerView:didAddMarker:

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

- rulerView:shouldAddMarker:

Returns whether a new marker can be added.

- rulerView:willAddMarker:atLocation:

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

- rulerView:handleMouseDown:

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

Dragging

- dragImageForSelectionWithEvent:origin:

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

- dragOperationForDraggingInfo:type:

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

- dragSelectionWithEvent:offset:slideBack:

Begins dragging the current selected text range.

acceptsGlyphInfo

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

Speaking Text

- startSpeaking:

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

- stopSpeaking:

Stops the speaking of text.

Working with Panels

usesFontPanel

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

usesFindPanel

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

- performFindPanelAction:

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

- orderFrontLinkPanel:

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

- orderFrontListPanel:

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

- orderFrontSpacingPanel:

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

- orderFrontTablePanel:

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

- orderFrontSubstitutionsPanel:

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

Text Completion

- complete:

Invokes completion in a text view.

- completionsForPartialWordRange:indexOfSelectedItem:

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

- insertCompletion:forPartialWordRange:movement:isFinal:

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

rangeForUserCompletion

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

Text Checking and Substitutions

- checkTextInDocument:

Performs the default text checking on the entire document.

- checkTextInSelection:

Performs the default text checking on the current selection.

- checkTextInRange:types:options:

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

- handleTextCheckingResults:forRange:types:options:orthography:wordCount:

Handles the text checking results returned by the text view

enabledTextCheckingTypes

The default text checking types.

automaticDashSubstitutionEnabled

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

- toggleAutomaticDashSubstitution:

Toggles the state of the automatic dash substitution.

automaticDataDetectionEnabled

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

- toggleAutomaticDataDetection:

Toggles the state of the automatic data detection.

automaticSpellingCorrectionEnabled

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

- toggleAutomaticSpellingCorrection:

Toggles the state of the automatic spelling correction.

automaticTextReplacementEnabled

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

- toggleAutomaticTextReplacement:

Toggles the state of the automatic text replacement.

Changing First Responder Status

- becomeFirstResponder

Informs the receiver that it’s becoming the first responder.

- resignFirstResponder

Notifies the receiver that it’s been asked to relinquish its status as first responder.

Supporting QuickLook

- updateQuickLookPreviewPanel

Notifies the QuickLook panel that an update may be required.

- toggleQuickLookPreviewPanel:

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

- quickLookPreviewableItemsInRanges:

Returns an array of URLs for items that can be displayed by QuickLook in the specified ranges.

Changing Layout Orientation

- changeLayoutOrientation:

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

- setLayoutOrientation:

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

Using the Find Bar

usesFindBar

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

incrementalSearchingEnabled

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 selectionRangeForProposedRange: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.

NSTextViewDidChangeSelectionNotification

Posted when the selected range of characters changes.

NSTextViewWillChangeNotifyingTextViewNotification

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

NSTextViewDidChangeTypingAttributesNotification

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

Initializers

See Also

Content Views

Browser View

Provide a column-based interface for viewing and navigating hierarchical information.

Collection View

Display one or more subviews in a highly configurable arrangement.

Outline View

Display a list-based interface for hierarchical data, where each level of hierarchy is indented from the previous one.

NSOpenGLView

A view that displays OpenGL content in a view.

Deprecated
Table View

Display custom data in rows and columns.