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

# smartInsert(beforeStringFor:replacing:)

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(beforeStringFor pasteString: String, replacing charRangeToReplace: NSRange) -> String?
```

## Parameters

`pasteString`

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

`charRangeToReplace`

The range of characters which `aString` is replacing.

## Return Value

Any whitespace that needs to be added before `aString` to preserve proper spacing and punctuation when the characters in `charRange` are replaced by  `aString`. If `aString` is `nil` or if smart insertion and deletion are disabled, this method returns `nil`.

## Discussion

Don’t invoke this method directly. Instead, use [`smartInsert(for:replacing:before:after:)`](/documentation/AppKit/NSTextView/smartInsert(for:replacing:before:after:)), which calls this method as part of its implementation.

---

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)