Clifton Labrum
Clifton Labrum

Reputation: 14088

Replace Substring with Markdown on NSTextView in Swift

Swift 5, Xcode 11

In a Stack Overflow text editor, you can select some text (like "selected" below), click the bold button, and it replaces:

Text selected here.

...with this:

Text **selected** here.

I'm trying to pull off the same thing with an NSTextView using Swift 5.

I can get the selectedRange of the text like this:

@IBAction func clickBold(_ sender: NSButton) {
  let range = content.selectedRange() //content is my NSTextView
}

But I can't figure out how to proceed from here. I found replaceSubrange but it seems to accept only a Range<String.Index> and not an NSRange.

@IBAction func clickBold(_ sender: NSButton) {
  let range = content.selectedRange() //content is my NSTextView
  var markdownText = content.string
  markdownText.replaceSubrange(range, with: "**\(markdownText)**") 
}

Has anyone done this before and can help me see what I'm missing? Thanks!

Upvotes: 1

Views: 739

Answers (2)

David Pasztor
David Pasztor

Reputation: 54745

You should use the replaceCharacters(in:with:) method of NSText (whose subclass NSTextView is).

@IBAction func clickBold(_ sender: NSButton) {
  let range = content.selectedRange()
  let selectedText = (content.string as NSString).substring(with: range)
  content.replaceCharacters(in: range, with: "**\(selectedText)**") 
}

Upvotes: 1

Clifton Labrum
Clifton Labrum

Reputation: 14088

It looks like this works:

let range = content.selectedRange()
markdownText = content.string

if let index = Range(range, in: markdownText){
  content.replaceCharacters(in: range, with: "**\(markdownText[index])**")
}

It provides the selected text snippet I need to wrap it in ** **. @MartinR's linked SO post helped me see that I can convert the string index with Range().

Upvotes: 0

Related Questions