Of course! Using Python with SourceInsight is a powerful way to automate tasks, analyze code, and enhance your workflow. SourceInsight has a built-in Python scripting interface that allows you to control almost every aspect of the editor.

Here’s a comprehensive guide covering everything from the basics to practical examples.
The Basics: How to Run Python in SourceInsight
SourceInsight comes with a Python interpreter built-in. You can run scripts in two main ways:
A. The Interactive Python Window (REPL)
This is the best place for quick testing and exploration.
- Open SourceInsight.
- Go to the menu:
View->New Command Window. - In the new window that appears, click on the dropdown (it might say "Command" or "Output") and select
Python. - You now have a Python interactive shell where you can type commands directly and see the results instantly.
B. Running a Python Script File
For more complex, reusable tasks, you'll write your code in a .py file and run it.

- Write your Python code in a text editor (or even the SourceInsight editor itself) and save it as a
.pyfile (e.g.,my_script.py). - In SourceInsight, go to the menu:
File->Run Command...(or pressCtrl+Shift+C). - In the dialog box, type
python "path\to\your\script.py"and click OK.
Important Note on Paths: The path in the Run Command dialog is relative to SourceInsight's working directory, which is usually its installation folder. It's often easier to use the full path or to place your script in a directory that's in your system's PATH.
The SourceInsight Python API
The real power comes from SourceInsight's COM (Component Object Model) API. This API lets your Python script interact with SourceInsight's internal objects like projects, files, symbols, and the editor window itself.
Key Objects in the API
App: The root application object. You get this first.Project: Represents a SourceInsight project.ProjectItem: Represents a single file within a project.File: Represents an open file buffer.Symbol: Represents a symbol (function, variable, class, etc.).Output: Represents an output window (like the "Output" pane).View: Represents an editor window or view.Edit: Provides methods for text manipulation in an editor view.
How to Use the API
You access these objects through the si module, which SourceInsight automatically imports in its Python environment.
# The standard way to start a SourceInsight script
import si
# Get the top-level application object
app = si.GetApp()
# Get the currently active project
project = app.GetActiveProject()
if project:
print(f"Active project: {project.GetName()}")
else:
print("No active project found.")
# Get the currently active file (the one in the focused editor)
file = app.GetActiveFile()
if file:
print(f"Active file: {file.GetName()}")
# Get the full path of the file
print(f"Full path: {file.GetPath()}")
Practical Examples
Let's look at some common tasks you can automate.

Example 1: List All Files in a Project
This script iterates through all items in the active project and prints their names.
import si
app = si.GetApp()
project = app.GetActiveProject()
if not project:
print("Error: No active project.")
si.Exit(1) # Exit with an error code
output = app.GetOutputWindow("Command") # Get the command window for output
output.Clear()
output.WriteLine("--- Files in Project: " + project.GetName() + " ---")
# Iterate through all project items
# Use a while loop because GetNextItem() moves the internal cursor
item = project.GetFirstProjectItem()
while item:
# Check if it's a file (not a folder)
if item.GetType() == si.kProjectItemFile:
output.WriteLine(item.GetName())
item = project.GetNextProjectItem()
output.WriteLine("--- End of List ---")
Example 2: Find and Replace Text in All Project Files
This is a classic automation task. This script finds all occurrences of a string and replaces it in every file within the active project.
Warning: Always back up your project before running a script that modifies files!
import si
app = si.GetActiveProject()
project = app.GetActiveProject()
if not project:
print("Error: No active project.")
si.Exit(1)
# --- CONFIGURATION ---
# The text to find and the text to replace it with
find_text = "OldClassName"
replace_text = "NewClassName"
# --- END CONFIGURATION ---
output = app.GetOutputWindow("Command")
output.Clear()
output.WriteLine(f"Starting find-and-replace: '{find_text}' -> '{replace_text}'")
item = project.GetFirstProjectItem()
files_changed = 0
while item:
if item.GetType() == si.kProjectItemFile:
file_path = item.GetPath()
output.WriteLine(f"Processing: {file_path}")
# Open the file for reading
file = app.OpenFile(file_path, si.kFileRead)
if not file:
output.WriteLine(f" -> Could not open file.")
item = project.GetNextProjectItem()
continue
# Read the entire content
content = file.GetContent()
file.Close() # Close the read handle
# Perform the replacement
new_content = content.replace(find_text, replace_text)
# If a change was made, write it back
if new_content != content:
output.WriteLine(f" -> Changes found. Writing back...")
# Open the file for writing
file = app.OpenFile(file_path, si.kFileWrite)
if file:
file.SetContent(new_content)
file.Close()
files_changed += 1
else:
output.WriteLine(f" -> ERROR: Could not open file for writing.")
else:
output.WriteLine(f" -> No changes.")
item = project.GetNextProjectItem()
output.WriteLine(f"\nDone. {files_changed} files were modified.")
Example 3: List All Functions in the Current File
This script uses the symbol table to find and list all function definitions in the currently active file.
import si
app = si.GetApp()
file = app.GetActiveFile()
if not file:
print("Error: No active file.")
si.Exit(1)
output = app.GetOutputWindow("Command")
output.Clear()
output.WriteLine(f"--- Functions in: {file.GetName()} ---")
# Get the symbol table for the file
symtab = file.GetSymbolTable()
if not symtab:
output.WriteLine("No symbol table found for this file.")
si.Exit(0)
# Iterate through all symbols in the file
sym = symtab.GetFirstSymbol()
while sym:
# We are only interested in function symbols
if sym.GetType() == si.kSymbolFunc:
func_name = sym.GetName()
# Get the line number where the symbol is defined
line_num = sym.GetLine()
output.WriteLine(f" - {func_name} (defined on line {line_num})")
sym = symtab.GetNextSymbol()
output.WriteLine("--- End of Function List ---")
Debugging Your Scripts
Debugging can be tricky. Here are a few strategies:
- Use the Interactive Window: For small snippets, run them line-by-line in the Python interactive window to see where things break.
- Print to Output: The most common method. Use
output.WriteLine("My variable value: " + str(my_variable))to inspect the state of your script at different points. - The
si.Exit(code)function: Usesi.Exit(1)to stop script execution immediately, which is useful for handling errors. - Logging: For complex scripts, write detailed logs to a file.
import si
import os
app = si.GetApp()
project = app.GetActiveProject()
# Create a log file in a temporary directory
log_file_path = os.path.join(os.environ["TEMP"], "si_script.log")
log_file = open(log_file_path, "w")
log_file.write("Script started.\n")
# ... your script logic ...
log_file.write("Processing item: " + item.GetName() + "\n")
# ...
log_file.close()
output = app.GetOutputWindow("Command")
output.WriteLine(f"Log written to: {log_file_path}")
Where to Find More Information
- SourceInsight's Built-in Help: This is the best resource.
- Go to
Help->Python API Reference. This opens a detailed help file with all the objects, methods, and their parameters. - Go to
Help->Python Sample Scripts. This directory contains many useful example scripts that demonstrate how to use the API.
- Go to
- Online Community: The [SourceInsight forums](https://sourceinsight
