<!--
{
  "availability" : [
    "macOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "AppKit",
  "identifier" : "/documentation/AppKit/NSTextView/smartInsert(for:replacing:before:after:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "AppKit"
    ],
    "preciseIdentifier" : "c:objc(cs)NSTextView(im)smartInsertForString:replacingRange:beforeString:afterString:"
  },
  "title" : "smartInsert(for:replacing:before:after:)"
}
-->

# smartInsert(for:replacing:before:after:)

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 smartInsert(for pasteString: String, replacing charRangeToReplace: NSRange, before beforeString: AutoreleasingUnsafeMutablePointer<NSString?>?, after afterString: AutoreleasingUnsafeMutablePointer<NSString?>?)
```

## Parameters

`pasteString`

The string that is replacing the characters in `charRange`.

`charRangeToReplace`

The range of characters which `aString` is replacing.

`beforeString`

On return, a pointer to the string with the characters that should be added before `aString`; `nil` if there are no characters to add, if `aString` is `nil`, or if smart insertion and deletion are disabled.

`afterString`

On return, a pointer to the string with the characters that should be added after `aString`; `nil` if there are no characters to add, if `aString` is `nil`, or if smart insertion and deletion are disabled.

## Discussion

As part of its implementation, this method calls [`smartInsert(afterStringFor:replacing:)`](/documentation/AppKit/NSTextView/smartInsert(afterStringFor:replacing:)) and [`smartInsert(beforeStringFor:replacing:)`](/documentation/AppKit/NSTextView/smartInsert(beforeStringFor:replacing:)). To change this method’s behavior, override those two methods instead of this one.

`NSTextView` uses this method as necessary. You can also use it in implementing your own methods that insert text. To do so, invoke this method with the proper arguments, then insert `beforeString`, `aString`, and `afterString` in order over `charRange`.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)