You will encounter two problems if trying to obtain the cursor's line and column number in an EditorGadget on MacOS X:
- You need to detect whenever the cursor changes its position in the EditorGadget. PureBasic currently won't detect this, so you have to establish a callback for the Cocoa method textViewDidChangeSelection:. This is an easy part.
- The underlying native control of the EditorGadget is the NSTextView. Inherited controls are NSText, NSView, NSResponder and NSObject. They (and their delegates) all don't offer the possibility to obtain the current cursor's line and column number although it's fairly easy and fast to obtain the current cursor's position index. If you want to obtain the cursor's line and column number from the cursor's position index, things become a little bit more complicated because you have to take word wrap into account. With
word wrap disabled you can simply count the lind feeds and calculate the current line of the cursor. But with
word wrap enabled you have to take into account the line feeds, the wrapping of lines without line feeds and the maximum number of visible characters per line at the current EditorGadget's width (and that on a word basis). Another problem would be that this approach would increasingly become slower with larger texts...
Therefore - and for the sake of simplicity - the following example demonstrates how to always display the current cursor's position index in the StatusBar (currently doesn't work in Unicode mode!):
Code: Select all
EnableExplicit
ImportC ""
sel_registerName(MethodName.S)
class_addMethod(Class.I, Selector.I, Implementation.I, Types.S)
EndImport
ProcedureC SelectionDidChangeCallback(Object.I, Selector.I, Notification.I)
Protected Range.NSRange
CocoaMessage(@Range, GadgetID(0), "selectedRange")
StatusBarText(0, 0, "Cursor position: " + Str(Range\location),
#PB_StatusBar_Center)
EndProcedure
Define AppDelegate.I = CocoaMessage(0, CocoaMessage(0, 0,
"NSApplication sharedApplication"), "delegate")
Define DelegateClass.I = CocoaMessage(0, AppDelegate, "class")
Define Range.NSRange
Define Selector.I = sel_registerName("textViewDidChangeSelection:")
OpenWindow(0, 270, 100, 180, 100, "EditorGadget")
CreateStatusBar(0, WindowID(0))
AddStatusBarField(#PB_Ignore)
EditorGadget(0, 10, 10, 160, 60, #PB_Editor_WordWrap)
SetGadgetFont(0, LoadFont(0, "Monaco", 13))
SetGadgetText(0, "The quick brown fox jumps over the lazy dog.")
SetActiveGadget(0)
class_addMethod(DelegateClass, Selector, @SelectionDidChangeCallback(), "v@:@")
CocoaMessage(0, GadgetID(0), "setDelegate:", AppDelegate)
; ----- Set cursor in front of 1st character
CocoaMessage(0, GadgetID(0), "setSelectedRange:@", @Range)
Repeat
Until WaitWindowEvent() = #PB_Event_CloseWindow