Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Disable Alt-Drag Selection on an NSTextView?

I do not know, and cannot find, the standard technical term for the drag-select functionality when the alt/option button is pressed over an NSTextView.

When alt is pressed, the crosshair appears and text can be selected/highlighted in columns/vertically, as in Xcode.

I would like to disable this functionality in my NSTextViews, how can I do that please?

like image 439
Giles Avatar asked Jan 21 '26 03:01

Giles


1 Answers

Digging into the disassembly of AppKit quickly reveals a hook which tells NSTextView whether the ALT+drag interaction should be enabled. It's the private method called _allowsMultipleTextSelectionByMouse. Altering its behavior does the trick but it is achievable only via private API. In this case, it should be pretty safe to do so.

There are following two ways for altering the aforementioned method:

Approach 1: NSUserDefaults

The method internally accesses the NSProhibitMultipleTextSelectionByMouse of NSUserDefaults. You can control the boolean value for this key on the app level. The downsides of this approach are:

  • It can possibly be reenabled by the users of your app (e.g. via the defaults command line tool).
  • It affects all instances of NSTextView in your app even those you don't necessarily want to alter.

Approach 2: Swizzling

The approach I decided to go with is a simple swizzle of this method in my subclass of NSTextView.

internal final class MyTextView: NSTextView {

    internal static func initializeClass() {
        try? MyTextView.swizzle(
            Selector(("_allowsMultipleTextSelectionByMouse")),
            with: #selector(getter: swizzled_allowsMultipleTextSelectionByMouse)
        )
    }

    @objc dynamic internal var swizzled_allowsMultipleTextSelectionByMouse: Bool {
        return false
    }

}

And somewhere in the app bootstrapping code like the main function you have to trigger the class initialization code by MyTextView.initializeClass().

The code snippet above uses my own wrapper around the swizzling API but there are surely some libraries out there to use or you can follow the advices from this article by PSPDFKit.

like image 126
Lukas Kubanek Avatar answered Jan 23 '26 09:01

Lukas Kubanek