With Xojo 2022 Release 1, you can use XojoScript to create Code Assistants for use with selected text in the Code Editor. Here’s a quick example of one that swaps the prefix of a comment:
// This script takes the current selected comment // and changes the comment prefix. Function Name() As String Return "Swap Comment Prefix" End Function Function CanEdit(selection As String) As Boolean // Check if comments starts with // or '. Return Left(selection, 2) = "//" Or Left(selection, 1) = "'" End Function Function Edit(selection As String) As String // Swap // with ' or swap ' with // If Left(selection, 1) = "'" Then Return Replace(selection, "'", "//") ElseIf Left(selection, 2) = "//" Then Return Replace(selection, "//", "'") End If End Function
This is not too lengthy, so let’s examine the parts. With a code assistant, there are three methods that are required: Name, CanEdit and Edit.
The Name() method returns a string containing the name that will appear in the Code Assistants menu. You can nest items using slashes, so “Paul/Swap Comments Prefix” would have this appear in Code Assistants->Paul->Swap Comments Prefix.
The CanEdit() method provides the code editor selection as a parameter. In this method you should return True if this code assistant is allowed to edit the selection. If you return True, the name will appear in the Code Assistants menu. If you return False it will not appear in the menu.
The code above checks if the selected text starts with the comment prefixes we want to swap: // or ‘.
The Edit() method is where you modify the selection, returning new text that will replace the selection in the Code Editor. This method does a single replace of “//“ with “’” and “’” with “//“.
Save the above script as SwapCommentPrefix.xojo_code_assistant and copy it to the Scripts folder in your IDE install folder.
If Xojo was running, you can tell it to reload those scripts by holding down Cmd (on Mac) or Control (Windows/Linux) when right-clicking.
Now type a comment like this:
‘ This is a comment.
Select that comment and right-click. Choose Code Assistants->Swap Comment Prefix.
The line now shows as:
// This is a comment.
For other sample Code Assistant scripts, go to Examples/Advanced/IDE Scripts/Code Assistants in the Xojo download folder.
Learn more in this video! Be sure to share your Code Assistant scripts in the forum!