Where am I? - IDE Improvement

Just starting out? Need help? Post your questions and find answers here.
dige
Addict
Addict
Posts: 1391
Joined: Wed Apr 30, 2003 8:15 am
Location: Germany
Contact:

Where am I? - IDE Improvement

Post by dige »

Hi guys,

I often search for something in the source code and then I want to know immediately in which procedure the location is.

Ideally, the current procedure would automatically be displayed in bold in the procedure list.


However, I could also imagine writing a small plugin for this.
My idea would be when the line number of the cursor changes,
but scroll through the source code line by line until the next procedure keyword is found. And then display this in a small overlay.

What would be the keywords I would have to search for to realise something like this?


Thank you very much for any help!

Kind regrads

Dige

Edit: found some cool stuff from STARGÅTE : https://www.purebasic.fr/english/viewto ... 0&#p377840
Looks like a good start to get the cursor position. :D

But how can I search the source code for the corresponding procedure name? 🤔
Last edited by dige on Mon Jan 22, 2024 11:26 am, edited 1 time in total.
"Daddy, I'll run faster, then it is not so far..."
zikitrake
Addict
Addict
Posts: 868
Joined: Thu Mar 25, 2004 2:15 pm
Location: Spain

Re: Where am I? - IDE Improvement

Post by zikitrake »

+1 to this. I'm currently using the wonderful RSBasic addon "Multicolor Procedure List", but it would be nice to have it as standard in the PB editor.

https://www.purebasic.fr/english/viewtopic.php?t=72884
PB 6.21 beta, PureVision User
dige
Addict
Addict
Posts: 1391
Joined: Wed Apr 30, 2003 8:15 am
Location: Germany
Contact:

Re: Where am I? - IDE Improvement

Post by dige »

zikitrake wrote: Mon Jan 22, 2024 11:25 am +1 to this. I'm currently using the wonderful RSBasic addon "Multicolor Procedure List", but it would be nice to have it as standard in the PB editor.

https://www.purebasic.fr/english/viewtopic.php?t=72884
Oh yes! I actually use that too. But when I needed it with the current procedure name, it didn't show me that I was currently in the procedure Main().
But it seems to work in general. Thanks for the hint. :D
"Daddy, I'll run faster, then it is not so far..."
User avatar
Kiffi
Addict
Addict
Posts: 1485
Joined: Tue Mar 02, 2004 1:20 pm
Location: Amphibios 9

Re: Where am I? - IDE Improvement

Post by Kiffi »

dige wrote: Mon Jan 22, 2024 11:09 amBut how can I search the source code for the corresponding procedure name? 🤔
German Forum: PB-Tool: Display the name of the current procedure https://www.purebasic.fr/german/viewtop ... 11#p324611
Hygge
AZJIO
Addict
Addict
Posts: 2143
Joined: Sun May 14, 2017 1:48 am

Re: Where am I? - IDE Improvement

Post by AZJIO »

FindAllReferences[Win] (Dadlick)
In its fork, the output of the procedures in which the entry was found was made, see the first line of the data output results.
Kiffi wrote: Mon Jan 22, 2024 11:40 am German Forum: PB-Tool: Display the name of the current procedure https://www.purebasic.fr/german/viewtop ... 11#p324611
I made my own changes to make the code faster. 0ms vs 93ms (6000 lines).

Code: Select all

; GetProcedureName

; #################################################################
; In den Werkzeug-Einstellungen als Argumente "%TEMPFILE" eintragen
; #################################################################

EnableExplicit

Global InitCountStr = 1000
Global Dim FileStr.s(InitCountStr)
Global CursorLine = Val(StringField(GetEnvironmentVariable("PB_TOOL_Cursor"), 1, "x"))

Define ScintillaText.s
Define Line.s
Define i, CountStr, char

If CountProgramParameters() < 1
	MessageRequester("Exit","Parameters = 0")
	End
EndIf

; https://www.purebasic.fr/english/viewtopic.php?t=79183
Procedure.s LTrimChar(String$, TrimChar$ = #CRLF$ + #TAB$ + #FF$ + #VT$ + " ")
    Protected *jc0, *c.Character, *jc.Character

    If Not Asc(String$)
        ProcedureReturn ""
    EndIf

    *c = @String$
    *jc0 = @TrimChar$

    While *c\c
        *jc = *jc0

        While *jc\c
            If *c\c = *jc\c
                *c\c = 0
                Break
            EndIf
            *jc + SizeOf(Character)
        Wend

        If *c\c
            String$ = PeekS(*c)
            Break
        EndIf
        *c + SizeOf(Character)
    Wend

    ProcedureReturn String$
EndProcedure


Procedure GetScintillaText()

	; thx to sicro (http://www.purebasic.fr/german/viewtopic.php?p=324916#p324916)

	Protected FilePath.s
	Protected File, BOM
	Protected i

	FilePath = ProgramParameter(0) ; %TEMPFILE (Datei existiert auch, wenn Code nicht gespeichert ist)

	File = ReadFile(#PB_Any, FilePath, #PB_File_SharedRead)
	If IsFile(File)
		BOM = ReadStringFormat(File) ; BOM überspringen, wenn vorhanden
		While Eof(File) = 0			 ; Цикл, пока не будет достигнут конец файла. (Eof = 'Конец файла')
			FileStr(i) = ReadString(File, BOM)
			i + 1
			If i > InitCountStr
				InitCountStr * 2
				ReDim FileStr(InitCountStr)
			EndIf
			If i > CursorLine
				Break
			EndIf
		Wend
		ReDim FileStr(i - 1)
		CloseFile(File)
	EndIf

EndProcedure


GetScintillaText()



CountStr = ArraySize(FileStr())
If CountStr > 2

	For i = CountStr - 1 To 0 Step - 1
		
		FileStr(i) = LTrimChar(FileStr(i), #TAB$ + " ")
		char = Asc(FileStr(i))

		If (char = 'e' Or char = 'E') And Left(LCase(FileStr(i)), 12) = "endprocedure"
			Break
		EndIf

		If (char = 'p' Or char = 'P') And Left(LCase(FileStr(i)), 9) = "procedure" And Left(LCase(FileStr(i)), 15) <> "procedurereturn"
			MessageRequester("You are here:", FileStr(i))
			Break
		EndIf

	Next

EndIf
User avatar
skywalk
Addict
Addict
Posts: 4211
Joined: Wed Dec 23, 2009 10:14 pm
Location: Boston, MA

Re: Where am I? - IDE Improvement

Post by skywalk »

This is the tool I use. Modified from kiffi's code.
With the cursor in the editor, press Ctrl+Q and the procedure list is highlighted where I am.

Code: Select all

;-{ ct_show_procedure.pb
; =================================================
; kiffi, https://www.purebasic.fr/german/viewtopic.php?f=8&t=28267
; GetProcedureName
; REV: 190606, skywalk
;      Modified to catch similarly named Procedures in ListBox.
;      Ex. ShowIt() and ShowIt2().
; REV: 190607, skywalk
;      Attempt to read process memory instead of temp file.
;      Ex. ShowIt() and ShowIt2().
; =================================================
; COMPILER OPTIONS:
;   [ ] Main source file:
;   [x] Use Compiler:   PureBasic 5.73 (Windows - x64)
;                       PureBasic 6.00 - C Backend (Windows - x64)
;   [x] Use Icon:       
;   [x] Optimize generated code
;   [ ] Enable inline ASM syntax coloring
;   [x] Create threadsafe executable
;   [ ] Enable OnError lines support
;   [x] Enable modern theme support (for Windows XP and above)
;   [ ] Request Administrator mode for Windows Vista and above
;   [ ] Request User mode for Windows Vista (no virtualisation)
;   [ ] Enable DPI aware executable (Windows)
;   [ ] Enable DLL preloading protection (Windows)
;   Library Subsystem:
;   Executable format:        Windows ;|Console|Shared DLL
;                             All CPU ;|Dynamic|w/MMX|w/3DNOW|w/SSE|w/SSE2
;   Linker options file:      
; COMPILE/RUN:
;   Debugger:
;     [x] Enable Debugger
;     [x] Enable Purifier
;     [ ] Use selected Debugger:      ;Integrated IDE Debugger
;     [ ] Use Warning mode:           ;Display Warnings
;   Run executable with:
;     Executable Commandline:         ;
;     Current directory:              ;C:\dev\tools\
;     [x] Create temporary executable in the source directory
; CONSTANTS:
; VERSION INFO:
;   [ ] Include Version Information
;   Update version info in:   auto set fields --> %yy.%mm.%dd
; RESOURCES:
;   C:\dev\tools\some-resource.rc
; IDE PREFERENCES:
;   Compiler:Defaults:
;     Sourcefile Text encoding: UTF-8
;   ToolsPanel:Configuration:Procedure Browser
;     [x] Sort Procedures by name       ;<-- Alphabetical instead of order of appearance. Uncheck when location of Proc desired.
;     [ ] Group Markers                 ;<-- If checked, ';-!' priority listing is lost.
;     [ ] Display Procedure Arguments   ;<-- Too busy if checked.
;   Editor:
;     Save Settings to: The end of the Source file
;                       | The file <filename>.pb.cfg | A common file project.cfg for every directory | Don't save anything
;     Tab Length:       2 [ ] Use real Tab (ASCII 9)
;     Source Directory: c:\dev\
;   Debugger: 
;     Choose Debugger Type:  Integrated IDE Debugger ;|Standalone GUI Debugger|Console only Debugger
;     Choose Warning level:  Display Warnings
; =========================================================================================================================
; TOOL SETTINGS: 
;   Compile to ct_show_procedure.exe as below.
;   Edit Tool Settings for each Case:
;   Ex. Commandline: ct_sci_all.exe
;       Arguments: %TEMPFILE
;       Working Directory:
;       Name: CT_SHOW_PROCEDURE
;       Event to trigger the tool: Menu or Shortcut: [Ctrl+Q]
;       [ ] Wait until tool quits
;       [ ] Run Hidden
;       [ ] Hide Editor
;       [ ] Reload Source after tool has quit
;           [x] into new source
;           [ ] into current source
;       [ ] Hide Tool from the Main menu
;       [ ] Enable Tool on a per-source basis
;       Supported File extensions (ext1,ext2,...): 
EnableExplicit
#SP$ = Chr(32)
#TAB$ = Chr(9)
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Windows
  #EOL$ = #CRLF$
CompilerDefault
  #EOL$ = #LF$
CompilerEndSelect
Global.s FilePath$
Procedure.s RemoveLeadingWhitespaceFromString(InString$)
  While Left(InString$, 1) = #SP$ Or Left(InString$, 1) = #TAB$
    InString$ = LTrim(InString$, #SP$)
    InString$ = LTrim(InString$, #TAB$)
  Wend
  ProcedureReturn InString$
EndProcedure
Procedure.s GetScintillaText()
  ; sicro, http://www.purebasic.fr/german/viewtopic.php?p=324916#p324916
  Protected.s r$
  Protected File, BOM
  FilePath$ = ProgramParameter(0); %TEMPFILE (file also exists if code is not saved)
  File = ReadFile(#PB_Any, FilePath$, #PB_File_SharedRead)
  If IsFile(File)
    BOM = ReadStringFormat(File)  ; Skip BOM if present
    r$ = ReadString(File, #PB_File_IgnoreEOL); | BOM)
    CloseFile(File)
    If FindString(FilePath$, "\Temp\", 1, #PB_String_NoCase)
      ; Only delete temp file, in case user enters wrong path in Tool options.
      DeleteFile(FilePath$)
    EndIf
  EndIf
  ProcedureReturn r$
EndProcedure
Procedure.i ct_hpID_from_hW(hW.i)
  ;         ct_pID_from_hW
  Protected.i pID, hpID
  If GetWindowThreadProcessId_(hW, @pID)
    hpID = OpenProcess_(#PROCESS_ALL_ACCESS, 0, pID)
  EndIf
  ProcedureReturn hpID
EndProcedure
Procedure.s ct_sci_GetText(hSci.i, hpid.i)
  ; REV:  180218, skywalk
  ; USE:  Get all text in current tab of editor.
  Protected.i ri, Length, Length2, Format
  Protected.i *mSci, *mtxt
  Protected.s txt$
  If hSci And hpid
    Select SendMessage_(hSci, #SCI_GETCODEPAGE, 0, 0)
    Case 0
      Format = #PB_Ascii
    Case 2, 65001
      Format = #PB_UTF8
    EndSelect
    MessageRequester("Format", Str(Format))
    Length = SendMessage_(hSci, #SCI_GETTEXT, 0, 0) + SizeOf(Character)
    MessageRequester("Length", Str(Length))
    MessageRequester("hpid", Str(hpid))
    *mtxt = AllocateMemory(Length+32)
    If *mtxt
      *mSci = VirtualAllocEx_(hpid, 0, Length, #MEM_RESERVE | #MEM_COMMIT, #PAGE_EXECUTE_READWRITE)
      MessageRequester("*mSci", Str(*mSci))
      If *mSci
        SendMessage_(hSci, #SCI_GETTEXT, 0, *mSci)
        ri = ReadProcessMemory_(hpid, *mSci, *mtxt, Length - SizeOf(Character), @Length2)
        MessageRequester("readprocessmemory", Str(ri))
        MessageRequester("length2", Str(length2))
        txt$ = PeekS(*mtxt, Length2, #PB_Ascii)
        Delay(30)
        VirtualFreeEx_(hpid, *mSci, Length, #MEM_RELEASE)
      EndIf
      MessageRequester("txt$", txt$)
      FreeMemory(*mtxt)
    EndIf
  EndIf
  ProcedureReturn txt$
EndProcedure
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
  Procedure EnumChildProc(hWnd, *lParam)
    Protected.i Count, i, Size, searchfull
    Protected.s Buffer, Buffer2
    Protected CName.s{128}
    GetClassName_(hWnd, @CName, 128)
    If CName = "ListBox"
      Count = SendMessage_(hWnd, #LB_GETCOUNT, #Null, #Null)
      For i = Count - 1 To 0 Step -1  ; Search bottom up to help search alphabetically.
        Size   = SendMessage_(hWnd, #LB_GETTEXTLEN, i, #Null)
        Buffer = Space(Size + 64)
        If SendMessage_(hWnd, #LB_GETTEXT, i, @Buffer)
          If searchfull = 0
            ; Check if parameters are shown in listview
            If FindString(Buffer, "(")
              searchfull = 1
            Else
              searchfull = -1
            EndIf
          EndIf
          If searchfull = 1
            If PeekS(*lParam) = Buffer
              SendMessage_(hWnd, #LB_SETCURSEL, i, #Null)
              ProcedureReturn 0
            EndIf
          Else
            Buffer2 = Trim(StringField(PeekS(*lParam), 1, "("))
            ;MessageRequester("In EnumChildProc", Buffer + " = " + Buffer2)
            If Buffer2 = Buffer
              SendMessage_(hWnd, #LB_SETCURSEL, i, #Null)
              ProcedureReturn 0
            EndIf
          EndIf
        EndIf
      Next i
    EndIf
    ProcedureReturn 1
  EndProcedure
CompilerEndIf
CompilerIf 0
  Procedure ShowIt2(Line$)
    ; Dummy procedure with nearly same name.
    ; Cursor here did not not select correct Procedure in ListBox.
  EndProcedure
CompilerEndIf
Procedure ShowIt(Line$)
  Protected.i hwnd, i
  Protected.s s$
  CompilerSelect #PB_Compiler_OS
  CompilerCase #PB_OS_Windows
    hwnd = Val(GetEnvironmentVariable("PB_TOOL_MainWindow"))
    i    = FindString(Line$, " ")
    If i = 0
      i = FindString(Line$, #TAB$)
    EndIf
    Line$ = Mid(Line$, i + 1)
    Line$ = RemoveLeadingWhitespaceFromString(Line$)
    ;MessageRequester("SHOWIT", Line$)
    EnumChildWindows_(hWnd, @EnumChildProc(), @Line$)
  CompilerDefault
    ;Linux / Mac?
    MessageRequester("You are here:", Line$)
  CompilerEndSelect
EndProcedure
;-{ START
Define.i i
Define.i CursorLine = Val(StringField(GetEnvironmentVariable("PB_TOOL_Cursor"), 1, "x"))
Define.s ScintillaText$, Line$
If 1
  ScintillaText$ = GetScintillaText()
Else  ;TBD; Get the text from current opened file instead of TEMPFILE.
  Define.i hSci = Val(GetEnvironmentVariable("PB_TOOL_Scintilla"))
  Define.i hIDE = Val(GetEnvironmentVariable("PB_TOOL_MainWindow"))
  Define.i hpid = ct_hpid_from_hW(hSci)
  If hSci And hpid
    ScintillaText$ = ct_sci_GetText(hSci, hpid)
    CloseHandle_(hpid)
  EndIf
EndIf
If ScintillaText$ <> #Empty$
  For i = CursorLine To 1 Step - 1
    Line$ = RemoveLeadingWhitespaceFromString(StringField(ScintillaText$, i, #EOL$))
    ;;MessageRequester("BEFORE SHOWIT", Line$)
    ; Allow EndProcedure to trigger search.
    ;If Left(LCase(Line$), Len("endprocedure")) = "endprocedure"
    ;  Break
    ;EndIf
    If Left(LCase(Line$), Len("procedure")) = "procedure"
      If Left(LCase(Line$), Len("procedurereturn")) <> "procedurereturn"
        ShowIt(Line$)
        Break
      EndIf
    EndIf
  Next i
EndIf
;-} STOP
;-} ct_show_procedure.pb
The nice thing about standards is there are so many to choose from. ~ Andrew Tanenbaum
AZJIO
Addict
Addict
Posts: 2143
Joined: Sun May 14, 2017 1:48 am

Re: Where am I? - IDE Improvement

Post by AZJIO »

Doesn't work with module (module::Procedure)
Updated. Added support for modules.

Code: Select all

; GetProcedureName

; #################################################################
; Enter "%TEMPFILE" as an argument in the tool settings. (only on Linux)
; #################################################################

EnableExplicit

Global InitCountStr = 1000
Global Dim FileStr.s(InitCountStr)
Global CursorLine = Val(StringField(GetEnvironmentVariable("PB_TOOL_Cursor"), 1, "x"))

Define ScintillaText.s
Define Line.s
Define i, CountStr, char

; https://www.purebasic.fr/english/viewtopic.php?t=79183
Procedure.s LTrimChar(String$, TrimChar$ = #CRLF$ + #TAB$ + #FF$ + #VT$ + " ")
    Protected *jc0, *c.Character, *jc.Character

    If Not Asc(String$)
        ProcedureReturn ""
    EndIf

    *c = @String$
    *jc0 = @TrimChar$

    While *c\c
        *jc = *jc0

        While *jc\c
            If *c\c = *jc\c
                *c\c = 0
                Break
            EndIf
            *jc + SizeOf(Character)
        Wend

        If *c\c
            String$ = PeekS(*c)
            Break
        EndIf
        *c + SizeOf(Character)
    Wend

    ProcedureReturn String$
EndProcedure


CompilerIf #PB_Compiler_OS = #PB_OS_Windows
	
	Global ScintillaHandle = Val(GetEnvironmentVariable("PB_TOOL_Scintilla"))
	
	
	Procedure EnumChildProc(hWnd, *lParam)
		Protected.i Count, i, Size, searchfull
		Protected.s Buffer, Buffer2
		Protected CName.s{128}
		GetClassName_(hWnd, @CName, 128)
		If CName = "ListBox"
			Count = SendMessage_(hWnd, #LB_GETCOUNT, #Null, #Null) ; число пунктов в списке
			For i = Count - 1 To 0 Step - 1  ; Поиск снизу вверх, чтобы облегчить поиск по алфавиту.
				Size = SendMessage_(hWnd, #LB_GETTEXTLEN, i, #Null) ; получить длину пункта
				Buffer = Space(Size + 64)
				If SendMessage_(hWnd, #LB_GETTEXT, i, @Buffer) ; получить текст пункта
					If searchfull = 0
						; Проверьте, отображаются ли параметры в списке
						If FindString(Buffer, "(")
							searchfull = 1
						Else
							searchfull = -1
						EndIf
					EndIf
					If searchfull = 1
						If FindString(Buffer, "::")
							Buffer = StringField(Buffer, 2, "::")
						EndIf
						If PeekS(*lParam) = Buffer
							SendMessage_(hWnd, #LB_SETCURSEL, i, #Null)
							ProcedureReturn 0
						EndIf
					Else
						If FindString(Buffer, "::")
							Buffer = StringField(Buffer, 2, "::")
						EndIf
						Buffer2 = Trim(StringField(PeekS(*lParam), 1, "("))
						If Buffer2 = Buffer
							SendMessage_(hWnd, #LB_SETCURSEL, i, #Null)
							ProcedureReturn 0
						EndIf
					EndIf
				EndIf
			Next i
		EndIf
		ProcedureReturn 1
	EndProcedure

; https://www.purebasic.fr/english/viewtopic.php?f=12&t=65159&p=486382&hilit=SplitL#p486382
Procedure Split(String.s, Array StringArray.s(1), Separator.s = " ")
	
	Protected S.String, *S.Integer = @S
	Protected.i asize, i, p, slen
	asize = CountString(String, Separator)
	slen = Len(Separator)
	ReDim StringArray(asize)
	
	*S\i = @String
	While i < asize
		p = FindString(S\s, Separator)
		StringArray(i) = PeekS(*S\i, p - 1)
		*S\i + (p + slen - 1) << #PB_Compiler_Unicode
		i + 1
	Wend
	StringArray(i) = S\s
	*S\i = 0
	
EndProcedure


Procedure GetScintillaText()
	Protected ReturnValue.s
	Protected length
	Protected buffer
	Protected processId
	Protected hProcess
	Protected result

	length = SendMessage_(ScintillaHandle, #SCI_GETLENGTH, 0, 0)
	If length
		length + 2
		buffer = AllocateMemory(length)
		If buffer
			SendMessageTimeout_(ScintillaHandle, #SCI_GETCHARACTERPOINTER, 0, 0, #SMTO_ABORTIFHUNG, 2000, @result)
			If result
				GetWindowThreadProcessId_(ScintillaHandle, @processId)
				hProcess = OpenProcess_(#PROCESS_ALL_ACCESS, #False, processId)
				If hProcess
					ReadProcessMemory_(hProcess, result, buffer, length, 0)
					ReturnValue = PeekS(buffer, -1, #PB_UTF8)
					CloseHandle_(hProcess)  ; <-- Axolotl, added acc. to MSDN
				EndIf
			EndIf
		EndIf
		FreeMemory(buffer)
	EndIf
	
	Split(ReturnValue, FileStr(), #CRLF$)
	ReDim FileStr(CursorLine)
; 	ProcedureReturn ReturnValue
EndProcedure

Procedure ShowIt(Line$)
	Protected hwnd, i, s$
	hwnd = Val(GetEnvironmentVariable("PB_TOOL_MainWindow"))
	i = FindString(Line$, " ")
	If i = 0
		i = FindString(Line$, #TAB$)
	EndIf
	Line$ = Mid(Line$, i + 1)
	Line$ = LTrimChar(Line$, #TAB$ + " ")
	EnumChildWindows_(hWnd, @EnumChildProc(), @Line$)
EndProcedure

CompilerElse
	
	
Define StartTime
StartTime = ElapsedMilliseconds()

Procedure GetScintillaText()

	; thx to sicro (http://www.purebasic.fr/german/viewtopic.php?p=324916#p324916)

	Protected FilePath.s
	Protected File, BOM
	Protected i

	If CountProgramParameters() < 1
		MessageRequester("Exit","Parameters = 0")
		End
	EndIf

	FilePath = ProgramParameter(0) ; %TEMPFILE (Datei existiert auch, wenn Code nicht gespeichert ist)

	File = ReadFile(#PB_Any, FilePath, #PB_File_SharedRead)
	If IsFile(File)
		BOM = ReadStringFormat(File) ; Пропустить BOM, сдвигая указатель на данные
		While Eof(File) = 0
			FileStr(i) = ReadString(File, BOM)
			i + 1
			If i > InitCountStr
				InitCountStr * 2
				ReDim FileStr(InitCountStr)
			EndIf
			If i > CursorLine
				Break
			EndIf
		Wend
		ReDim FileStr(i - 1)
		CloseFile(File)
	EndIf

EndProcedure

Procedure ShowIt(Line$)
	MessageRequester(Str(ElapsedMilliseconds() - StartTime) + " ms, You are here:", Line$)
EndProcedure

CompilerEndIf



GetScintillaText()


CountStr = ArraySize(FileStr())
If CountStr > 2

	For i = CountStr - 1 To 0 Step - 1
		
		FileStr(i) = LTrimChar(FileStr(i), #TAB$ + " ")
		char = Asc(FileStr(i))

		If (char = 'e' Or char = 'E') And Left(LCase(FileStr(i)), 12) = "endprocedure"
			Break
		EndIf

		If (char = 'p' Or char = 'P') And Left(LCase(FileStr(i)), 9) = "procedure" And Left(LCase(FileStr(i)), 15) <> "procedurereturn"
			ShowIt(FileStr(i))
			Break
		EndIf

	Next

EndIf
Last edited by AZJIO on Tue Jan 23, 2024 1:53 pm, edited 3 times in total.
dige
Addict
Addict
Posts: 1391
Joined: Wed Apr 30, 2003 8:15 am
Location: Germany
Contact:

Re: Where am I? - IDE Improvement

Post by dige »

Thank you guys! Here is my attempt, based on Kiffis & Skywalks code.
Made some changes, to have a realtime support.

Code: Select all


EnableExplicit

Global InitCountStr = 1000
Global Dim FileStr.s(InitCountStr)
Global CursorLine
Global TempFile.s, FileName.s
Global ScintillaID.i = Val(GetEnvironmentVariable("PB_TOOL_Scintilla"))
Global TimeStamp = Date()

Define ScintillaText.s
Define Line.s
Define i, CountStr, char

If CountProgramParameters() < 2
	MessageRequester("Run as IDE Tool", ~"Arguments: \"%TEMPFILE\" \"%FILE\"")
	End
EndIf

; https://www.purebasic.fr/english/viewtopic.php?t=79183
Procedure.s LTrimChar(String$, TrimChar$ = #CRLF$ + #TAB$ + #FF$ + #VT$ + " ")
    Protected *jc0, *c.Character, *jc.Character

    If Not Asc(String$)
        ProcedureReturn ""
    EndIf

    *c = @String$
    *jc0 = @TrimChar$

    While *c\c
        *jc = *jc0

        While *jc\c
            If *c\c = *jc\c
                *c\c = 0
                Break
            EndIf
            *jc + SizeOf(Character)
        Wend

        If *c\c
            String$ = PeekS(*c)
            Break
        EndIf
        *c + SizeOf(Character)
    Wend

    ProcedureReturn String$
EndProcedure
Procedure.i GetScintillaText()
	Protected File, BOM, Pos
	Protected i
	Static LastCursor = #PB_Any
	
	;CursorLine = Val(StringField(GetEnvironmentVariable("PB_TOOL_Cursor"), 1, "x")) ; Not updated
	
	
	Pos        = SendMessage_ (ScintillaID, #SCI_GETCURRENTPOS, 0, 0)
	CursorLine = SendMessage_ (ScintillaID, #SCI_LINEFROMPOSITION, Pos, 0)
	
	SetGadgetText(0, "Line: " + Str(CursorLine + 1) + "  |  Pos: " + Str(Pos + 1))
	
	If CursorLine = LastCursor
	  ProcedureReturn #PB_Any
	EndIf
	
	FreeArray(FileStr())
	InitCountStr = 1000
  Dim FileStr(InitCountStr)
	
	LastCursor = CursorLine
	
  File = ReadFile(#PB_Any, TempFile, #PB_File_SharedRead)
  
  If IsFile(File)
    
    BOM = ReadStringFormat(File)
		
		While Eof(File) = 0
			FileStr(i) = ReadString(File, BOM)
			i + 1
			
			If i > InitCountStr
				InitCountStr * 2
				ReDim FileStr(InitCountStr)
			EndIf
			
			If i > CursorLine
				Break
			EndIf
		Wend
		
		If i > 1
		  InitCountStr = i + 1000
		  ReDim FileStr(InitCountStr)
		EndIf
		
		CloseFile(File)
	EndIf
	
	ProcedureReturn CursorLine

EndProcedure

Procedure Update()
  Protected CountStr, char, i
  Static lock
  
  
  If lock
	  ProcedureReturn
	EndIf

	lock = #True
	
  If GetScintillaText() <> #PB_Any
  
    CountStr = ArraySize(FileStr())
    
    If CountStr > 2
      
      SetGadgetText(1, "")
      
    	For i = CountStr - 1 To 0 Step - 1
    		
    		FileStr(i) = LTrimChar(FileStr(i), #TAB$ + " ")
    		char = Asc(FileStr(i))
    
    		If (char = 'e' Or char = 'E') And Left(LCase(FileStr(i)), 12) = "endprocedure"
    			Break
    		EndIf
    
    		If (char = 'p' Or char = 'P') And Left(LCase(FileStr(i)), 9) = "procedure" And Left(LCase(FileStr(i)), 15) <> "procedurereturn"
    		  SetGadgetText(1, Str(i + 1) + ": " + FileStr(i))
    			Break
    		EndIf
    
    	Next
    
    EndIf
    
  EndIf
  
  lock = #False
  
EndProcedure

Procedure ErrorHandler()
  Protected ErrorMessage$
  
  ErrorMessage$ = "A program error was detected:" + Chr(13)
  ErrorMessage$ + Chr(13)
  ErrorMessage$ + "Error Message:   " + ErrorMessage()      + Chr(13)
  ErrorMessage$ + "Error Code:      " + Str(ErrorCode())    + Chr(13)
  ErrorMessage$ + "Code Address:    " + Str(ErrorAddress()) + Chr(13)
 
  If ErrorCode() = #PB_OnError_InvalidMemory
    ErrorMessage$ + "Target Address:  " + Str(ErrorTargetAddress()) + Chr(13)
  EndIf
 
  If ErrorLine() = -1
    ErrorMessage$ + "Sourcecode line: Enable OnError lines support to get code line information." + Chr(13)
  Else
    ErrorMessage$ + "Sourcecode line: " + Str(ErrorLine()) + Chr(13)
    ErrorMessage$ + "Sourcecode file: " + ErrorFile() + Chr(13)
  EndIf
 
  MessageRequester("Crash Report", ErrorMessage$)
  End
 
EndProcedure
Procedure WindowResize()
  ResizeGadget(0, #PB_Ignore, #PB_Ignore, WindowWidth(0)-20, #PB_Ignore)
  ResizeGadget(1, #PB_Ignore, #PB_Ignore, WindowWidth(0)-20, WindowHeight(0) - 35)
  
EndProcedure

Procedure Main()
  Protected x, Event, txt.s, duration
  
  OnErrorCall(@ErrorHandler())
  
  If ExamineDesktops()
    x = DesktopWidth(0)
  EndIf  
  
  OpenWindow(0, x-400, 0, 400, 75, FileName, #PB_Window_SystemMenu|#PB_Window_MinimizeGadget|#PB_Window_SizeGadget)
  TextGadget(0, 10, 5, 380, 20, "Line: ")
  TextGadget(1, 10, 30, 380, 40, "")
  StickyWindow(0, #True)
  SetWindowColor(0, #Black)
  SetGadgetColor(0, #PB_Gadget_FrontColor, #Gray)
  SetGadgetColor(1, #PB_Gadget_FrontColor, #Green)
  SetGadgetColor(0, #PB_Gadget_BackColor, #Black)
  SetGadgetColor(1, #PB_Gadget_BackColor, #Black)
  
  TempFile = ProgramParameter(0) ; %TEMPFILE (Datei existiert auch, wenn Code nicht gespeichert ist)
  FileName = GetFilePart(ProgramParameter(1), #PB_FileSystem_NoExtension)
  
  Update()
  
  AddWindowTimer(0, 0, 1000)
  
  BindEvent(#PB_Event_SizeWindow, @WindowResize())
  
  Repeat
    Event = WaitWindowEvent()
    
    If Event = #PB_Event_Timer And EventTimer() = 0
      txt = FileName + " [" + FormatDate("%dd.%mm.%yyyy %hh:%ii:%ss", Date()) + "]  ⏲ "
      
      duration = Date() - TimeStamp
      
      If duration < 60
        txt + Str(duration) + "sek."
      ElseIf duration < 3600
        txt + Str(duration/60) + "min"
        
      Else
        txt + FormatDate("%hh:%ii", duration) + "h"
      EndIf
      
      SetWindowTitle(0, txt )
      Update()
      
    EndIf    
    
  Until Event = #PB_Event_CloseWindow  
  
EndProcedure

Main()

"Daddy, I'll run faster, then it is not so far..."
User avatar
Piero
Addict
Addict
Posts: 865
Joined: Sat Apr 29, 2023 6:04 pm
Location: Italy

Re: Where am I? - IDE Improvement

Post by Piero »

Code: Select all

; PureBasic IDE Tool with Arguments: "%TEMPFILE" %CURSOR

tf$ = ProgramParameter()
lin = Val(StringField(ProgramParameter(),1,"x"))

If ReadFile(0, tf$)
   enc = ReadStringFormat(0)
   For k = 1 To lin : src$ + ReadString(0,enc) + ~"\r" : Next
   CloseFile(0)
EndIf

Dim Result$(0)
If CreateRegularExpression(0, "(?<=(^procedure)).+", 
      #PB_RegularExpression_NoCase|#PB_RegularExpression_AnyNewLine|
      #PB_RegularExpression_MultiLine)
   NbFound = ExtractRegularExpression(0,src$,result$())
EndIf

if Result$(0)
   MessageRequester("Procedure:", Trim(Result$(NbFound - 1)), 
      #PB_MessageRequester_Ok | #PB_MessageRequester_Info)
EndIf
User avatar
Piero
Addict
Addict
Posts: 865
Joined: Sat Apr 29, 2023 6:04 pm
Location: Italy

Re: Where am I? - IDE Improvement

Post by Piero »

Code: Select all

; PureBasic IDE Tool with Arguments: "%TEMPFILE" %CURSOR

tf$ = ProgramParameter()
lin = Val(StringField(ProgramParameter(),1,"x"))

If ReadFile(0, tf$)
   enc = ReadStringFormat(0)
   For k = 1 To lin : src$ + ReadString(0,enc) + ~"\r" : Next
   CloseFile(0)
EndIf

Dim Result$(0)
If CreateRegularExpression(0, "(?<=(^(?=([^\s;])))).+", 
      #PB_RegularExpression_NoCase|#PB_RegularExpression_AnyNewLine|
      #PB_RegularExpression_MultiLine)
   NbFound = ExtractRegularExpression(0,src$,result$())
EndIf

if Result$(0)
   MessageRequester("Result:", Trim(Result$(NbFound - 1)), 
      #PB_MessageRequester_Ok | #PB_MessageRequester_Info)
EndIf
User avatar
Piero
Addict
Addict
Posts: 865
Joined: Sat Apr 29, 2023 6:04 pm
Location: Italy

Re: Where am I? - IDE Improvement

Post by Piero »

Code: Select all

; PureBasic IDE Tool with Arguments: "%TEMPFILE" %CURSOR

If ReadFile(0, ProgramParameter())
   lin = Val(StringField(ProgramParameter(), 1, "x"))
   enc = ReadStringFormat(0)
   For k = 1 To lin
      src$ + ReadString(0,enc) + ~"\n"
   Next
   CloseFile(0)
   If CreateRegularExpression(0, "^[^\s;].+", #PB_RegularExpression_NoCase|#PB_RegularExpression_MultiLine)
      Dim Result$(0)
      NbFound = ExtractRegularExpression(0, src$, Result$())
      if NbFound
         MessageRequester("Result:", Trim(Result$(NbFound - 1)), #PB_MessageRequester_Ok|#PB_MessageRequester_Info)
      EndIf
   EndIf
EndIf
Al_the_dutch
User
User
Posts: 70
Joined: Mon Nov 11, 2013 11:07 am
Location: Portugal

Re: Where am I? - IDE Improvement

Post by Al_the_dutch »

Ideally, the current procedure would automatically be displayed in bold in the procedure list.
+1 to that!!!
Post Reply