How can you intercept an insert in an NSTextView to remove unsupported formatting?

I am trying to create a simple window based on NSTextView for simple WYSIWYG editing. However, I only want to allow certain types of formatting (for example, Bold, Italic, Underline and one header type, but without colors or different fonts.)

The problem is that if I just use NSTextView, someone can create or copy the formatted text into another program, and then just paste it into this view, and all this formatting goes with it, allowing things that I don't allow, for example , different fonts, colors, etc.

In the best case, I want to automatically turn off any formatting that my application does not support. In the worst case, I just want to intercept the insert and change it to plain text, although they will have to manually reformat it manually. But this is preferable to incorrect formatting.

Note. Something similar has been set here in SO several times, but they are usually referenced on the Internet or using JavaScript / JQuery. I specifically refer to the use of NSTextView in a Mac application, so please be sure to refer to another question before just marking this as a duplicate. Thanks.

+6
source share
2 answers

In a subclass of NSTextView:

override func paste(_ sender: Any?) { pasteAsPlainText(sender) } 
+1
source

[Edit: see Joshua Nozzi's comment!]

One possible solution would be to make your NSTextView implement this template method:

 - (void)paste:(id)sender { NSPasteboard *pb = [NSPasteboard generalPasteboard]; //receive formatted string from pasteboard //remove formatting from string //put back plaintext string into pasteboard [super paste:sender]; //put back initial formatted string } 

This way, you do not need to handle any actual insert / insert, but it can go bad with cardboard before the actual insert.

You can also learn these NSTextView methods regarding pasteboard:

  • preferredPasteboardTypeFromArray:restrictedToTypesFromArray:
  • readSelectionFromPasteboard:
  • readSelectionFromPasteboard:type:
  • readablePasteboardTypes
  • writablePasteboardTypes
  • writeSelectionToPasteboard:type:
  • writeSelectionToPasteboard:types:
  • validRequestorForSendType:returnType:
+2
source

Source: https://habr.com/ru/post/901915/


All Articles