# PSPad User Script (JScript) — AI Specification

Portable specification for generating PSPad user scripts in **JScript** (Windows Script Host). Any AI can use this document without access to the PSPad source tree.

**Format version:** based on PSPad `uScripts.pas` (WSH / Active Scripting via `lvkActiveScript`).

---

## 1. How to create a user script (for humans)

### 1.1 Quick steps

1. **Use any AI** (ChatGPT, Claude, Cursor, etc.).
2. **Attach** this file: `PSPad-User-Script-JScript-AI-Spec.md` (from `Win32\Docs\` in the PSPad tree, or copy it from your PSPad installation folder).
3. **Send a prompt** like the one in Section 1.2 (fill in your functionality and menu name).
4. **Save the result** as a `.js` file:
   - **Portable PSPad** (runs from its own folder):  
     `.\Script\JScript\<YourScript>.js`  
     (relative to the PSPad executable directory, e.g. `PSPad\Win32\Script\JScript\`)
   - **Installed PSPad** (multi-user / per-user data):  
     `%AppData%\PSpad\Script\JScript\<YourScript>.js`
5. In PSPad: **Script → Recompile scripts** (or restart PSPad). The new command appears under the **Script** menu.

### 1.2 Copy-paste prompt (simple)

Replace the placeholders, then send together with the attached specification file:

```
Based on the attached specification, create a PSPad editor user script that will <describe functionality>.

Menu item name: <your name in the Script menu>
```

Optional: add submenu name, keyboard shortcut, or extra requirements (see Section 2.2 for a detailed template).

### 1.3 After you receive the script

1. Save the AI output as a single file with the **`.js`** extension (JScript).
2. Put it in the correct folder (Section 1.1, step 4).
3. Enable **Program settings → System integration → Integrated scripting support (WSH)** if scripting is not active yet.
4. **Script → Recompile scripts** and test the new menu item.

**Prerequisites:**

- Windows Script Host (WSH) must be installed and enabled.
- Integrated scripting support (WSH) must be enabled in PSPad settings.

---

## 2. Copy-paste prompts for AI

### 2.1 System prompt

Copy everything inside the block below as the system (or first) message:

```
You are an expert at creating PSPad user scripts in JScript (Windows Script Host).

You MUST follow the specification in "PSPad User Script (JScript) — AI Specification".

Rules:
1. Output a COMPLETE, valid .js file — no placeholders like "add logic here".
2. Use ONLY API functions documented in the specification. Never invent new PSPad API calls.
3. Every script module MUST define `var module_name = "UniqueName"` (unique across all scripts).
4. Every script module MUST define `function Init()` that registers menu items via addMenuItem().
5. Use WSH JScript syntax: var, function, no import/require, no ES6 modules.
6. Global PSPad API functions (echo, newEditor, addMenuItem, …) are called WITHOUT a prefix.
7. Editor operations require: var ed = newEditor(); ed.assignActiveEditor(); (or assign by index/name).
8. addMenuItem() works ONLY inside Init() — never call it from handler functions.
9. Handler function names passed to addMenuItem must match defined function names exactly.
10. After the .js file, provide: (a) brief description of behavior, (b) installation steps, (c) any limitations.

Do not use assignLog() — it is obsolete; use logAddLine(), logClear(), etc.
Do not use modern browser-only APIs (fetch, Promise, import).
Prefer camelCase API names as documented (assignActiveEditor, not AssignActiveEditor).
```

### 2.2 User prompt template (detailed)

Use this when the simple prompt in Section 1.2 is not enough:

```
Based on the attached specification, create a PSPad editor user script that will <describe functionality>.

Menu item name: <your name in the Script menu>

Module name: {UniqueModuleName — unique identifier, no spaces}
Submenu: {e.g. "Text tools" or leave empty for top-level Script menu}
Optional shortcut: {e.g. CTRL+ALT+S or none}

Behavior:
{Describe what the script should do when the menu item is clicked}

Input source:
- Active editor / selection / all open editors / project files / user dialog

Output target:
- Modify active editor / new editor tab / LOG window / message box

External dependencies:
{e.g. none, FileSystemObject, FTP, project API}

Special requirements:
{e.g. preserve undo, case-sensitive search, require selection, etc.}
```

---

## 3. Architecture overview

PSPad scripts are **JScript files** loaded by Windows Script Host at startup. Each file is one module. The `Init()` function registers menu items; clicking a menu item calls the registered handler function.

```
Script/JScript/MyScript.js  →  PSPad scans on startup  →  eval(module_name)  →  Call Init()  →  Menu items created
                                                                                              ↓
                                                                              User clicks menu → handler function runs
```

| Concept | Detail |
|---------|--------|
| **Engine** | Windows Script Host (WSH) via Active Scripting (`lvkActiveScript`) |
| **File location** | Portable: `<PSPad>\Script\JScript\*.js` — Installed per-user: `%AppData%\PSpad\Script\JScript\*.js` |
| **Module** | One `.js` file = one module; `module_name` must be unique |
| **Entry point** | `function Init()` — called once at startup; register menus here |
| **Global API** | Functions like `echo`, `newEditor`, `addMenuItem` are globally available (no prefix) |
| **Editor object** | `newEditor()` returns an editor handle object (`TEditor`) |
| **Cross-module calls** | `OtherModuleName.functionName()` — call functions from other script modules |
| **Reload** | After editing a script: **Script → Recompile scripts** or restart PSPad |

### 3.1 Startup sequence

1. PSPad calls `InitializeScripts` (if WSH scripting is enabled).
2. All `*.*` files in `Script\JScript\` are loaded (backup files `*.BAK` and files with `~` in extension are skipped).
3. Each file's `module_name` variable is evaluated; it must be unique.
4. If `Init` exists, it is called — this is the **only** time `addMenuItem` has effect.
5. Menu items appear under **Script** (and optional submenus).

### 3.2 Enumeration

`TEditorList` and `TEditor` support `for…in` iteration:

```javascript
// Iterate all open editor tabs (each ed is an editor object)
for (var ed in global) {
  // ed is activated automatically
}

// Iterate lines of an assigned editor (each line is a string)
var ed = newEditor();
ed.assignActiveEditor();
for (var line in ed) {
  // line is the line text
}
```

---

## 4. Required module structure

### 4.1 Minimal skeleton

```javascript
var module_name = "MyUniqueModule";
var module_ver = "1.0";

function myHandler() {
  var ed = newEditor();
  ed.assignActiveEditor();
  echo("Hello from " + module_name);
}

function Init() {
  addMenuItem("My Command", "", "myHandler");
}
```

### 4.2 Module metadata

| Variable | Required | Description |
|----------|----------|-------------|
| `module_name` | **Yes** | Unique module identifier (string). Used for cross-module calls and `moduleFileName()`. |
| `module_ver` | No | Version string; returned by `moduleVersion(module_name)`. |
| `module_author` | No | Convention only; not used by PSPad engine. |

### 4.3 Menu registration (`addMenuItem`)

```javascript
addMenuItem(caption, submenu, handlerFunctionName [, shortcut]);
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `caption` | string | Menu item text. Use `&` before a letter for keyboard accelerator (e.g. `"&Sort"`). Use `"-"` for a separator line. |
| `submenu` | string | Submenu caption under **Script**. Empty string `""` = top-level Script menu. Same submenu name groups items. |
| `handlerFunctionName` | string | Name of the function to call (string, not a function reference). |
| `shortcut` | string | Optional. e.g. `"CTRL+ALT+S"`. See PSPad shortcut documentation. |

**Critical:** `addMenuItem` only works during `Init()`. Calls at any other time are silently ignored.

**Example with submenu and shortcut:**

```javascript
function Init() {
  var menuName = "&" + module_name;
  addMenuItem("&Main action", menuName, "doWork");
  addMenuItem("Show version", menuName, "showVersion", "CTRL+ALT+1");
  addMenuItem("-", menuName, "");
}
```

### 4.4 Getter/setter pattern

Many editor and global functions support **get** (no arguments) and **set** (one argument):

```javascript
var text = ed.text();       // get all text
ed.text("new content");     // replace all text

var x = ed.caretX();        // get caret column
ed.caretX(10);              // set caret column

var ro = ed.readOnly();     // get read-only state
ed.readOnly(true);          // set read-only
```

---

## 5. Complete API reference

All functions below are globally available in JScript scripts unless noted as methods on an editor object returned by `newEditor()`.

### 5.1 Menu and module (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `addMenuItem` | `(caption, submenu, handler [, shortcut])` | `1` | Creates a Script menu item. **Only during Init().** |
| `moduleExists` | `(moduleName)` | `1` or `0` | Whether a script module is loaded. |
| `moduleVersion` | `(moduleName)` | string | Value of `module_ver` for the module, or `" "` if not found. |
| `moduleFileName` | `(moduleName)` | string | Full path to the module's `.js` file. |
| `modulePath` | `()` | string | Path to `Script\JScript\` folder (with trailing backslash). |

### 5.2 Editor management (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `newEditor` | `()` | editor object | Creates a new editor handle. Does not open a file until you call `newFile` / `openFile` / `assignActiveEditor`. |
| `editorsCount` | `()` | number | Number of currently open editor tabs. |
| `closeEditorByIndex` | `(index)` | `1` on success | Closes editor tab by index (0-based). |
| `closeEditorByTitle` | `(fileName)` | `1` on success | Closes editor by file name / tab title. |
| `closeAllEditors` | `()` | — | Closes all editor windows (same as Close All). |

### 5.3 PSPad information (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `pspadVersion` | `()` | string | PSPad version string. |
| `pspadPath` | `()` | string | PSPad application directory path. |
| `pspadClosing` | `()` | boolean | `true` if PSPad is shutting down. |
| `mainWindowHandle` | `()` | number | Main window HWND (for advanced interop). |
| `getVarValue` | `(variable [, fileName])` | string | Resolves a PSPad variable (e.g. `"%FileName%"`). Optional second arg for file-related variables. |

### 5.4 User interface (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `echo` | `(text)` | — | Shows an information message box with OK. |
| `inputText` | `(prompt, default [, cancelValue])` | string | Input dialog. Returns entered text, or `cancelValue` / `""` if cancelled. |
| `sleep` | `(milliseconds)` | — | Pauses script; processes pending UI messages. |
| `setWaitCursor` | `([true/false])` | — | `true` = hourglass cursor; `false` or no arg = default cursor. |
| `setClipboardText` | `(text)` | — | Puts text on the clipboard. |
| `getClipboardText` | `()` | string | Gets text from the clipboard. |
| `tabsToSpaces` | `(text)` | string | Expands tab characters to spaces using PSPad tab width setting. |

### 5.5 LOG window (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `logClear` | `()` | — | Clears the LOG window. |
| `logAddLine` | `(text)` | — | Appends a line to the LOG window (shows LOG if hidden). |
| `logGetLine` | `(index)` | string | Gets line at index (0-based). |
| `logSetLine` | `(index, text)` | — | Replaces line at index. |
| `logLinesCount` | `()` | number | Number of lines in LOG. |
| `logLineIndex` | `([index])` | number | Get current line index, or set current line. |
| `logSetTypeMemo` | `()` | — | LOG mode: free text (memo). |
| `logSetTypeList` | `()` | — | LOG mode: list with error marks. |
| `logSetParser` | `(parserString)` | — | Sets LOG parser string. |
| `logIsVisible` | `()` | boolean | Whether LOG panel is visible. |

### 5.6 Project (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `projectFilesCount` | `()` | number | Number of files in the current project. |
| `projectFiles` | `(index)` | string | File path at index (0-based). |
| `projectFileName` | `()` | string | Full path to the project file (`.psp`); empty if no project. |
| `projectItemsCount` | `()` | number | Total project tree items (files + folders). |
| `projectItems` | `(index)` | string | Item text at index. |
| `projectItemType` | `(index)` | number | `2` = file, `1` = folder, `-1` = invalid index. |
| `projectSave` | `()` | `1` | Saves the current project. |

### 5.7 FTP (global)

Requires an active FTP connection in PSPad.

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `ftpConnect` | `(connectionName)` | — | Connect to a predefined FTP connection. |
| `ftpDisconnect` | `()` | — | Disconnect FTP. |
| `ftpCommand` | `(command)` | string | Send raw FTP command (e.g. `"CWD /public"`). |
| `ftpDownloadFile` | `(remotePath, localPath)` | `1` on success | Download file from FTP. |
| `ftpUploadFile` | `(localPath, remotePath [, refresh])` | `1` on success | Upload file to FTP. |
| `ftpRefresh` | `()` | — | Refresh FTP directory listing. |

### 5.8 PSPad actions (global)

| Function | Signature | Returns | Description |
|----------|-----------|---------|-------------|
| `runPSPadAction` | `(actionName)` | boolean | Executes a PSPad action by name (e.g. `"aSave"`). Returns `true` if found and enabled. See PSPad help **PSPad Actions** for action names. |
| `reloadClips` | `()` | — | Reloads code template / clip storage. |
| `reloadUserHighlighter` | `(iniFileName)` | — | Reloads a user highlighter INI (name without path, extension optional). |

### 5.9 Editor object — assignment

Obtain with `var ed = newEditor();` then assign a document:

| Method | Signature | Returns | Description |
|--------|-----------|---------|-------------|
| `assignActiveEditor` | `()` | `1` on success | Bind to the currently active editor tab. |
| `assignEditorByIndex` | `(index)` | `1` on success | Bind to editor tab by index (0-based). |
| `assignEditorByName` | `(fileName)` | `1` on success | Bind to editor by file name / tab title. |
| `assignLog` | `()` | `0` | **Obsolete.** Use `logAddLine` etc. instead. |

### 5.10 Editor object — files

| Method | Signature | Returns | Description |
|--------|-----------|---------|-------------|
| `newFile` | `([fileName])` | — | Creates a new empty document (optional file name). |
| `openFile` | `(path)` | `1` on success | Opens an existing file. |
| `saveFile` | `()` | `1` on success | Saves the current file. |
| `saveFileAs` | `(path)` | `1` on success | Saves under a new path. |
| `reloadFile` | `()` | `1` on success | Reloads file from disk. |
| `closeFile` | `()` | `1` on success | Closes the bound editor. |
| `printFile` | `(showDialog)` | `1` on success | Prints; `true` = show print dialog. |
| `openFileFromFTP` | `(remotePath)` | — | Opens file from connected FTP. |
| `saveFileToFTP` | `()` | `1` on success | Saves current file to FTP. |
| `activate` | `()` | `1` on success | Brings the bound editor to front / focus. |
| `fileName` | `([path])` | string | Get or set the file name / path. |

### 5.11 Editor object — state

| Method | Signature | Returns | Description |
|--------|-----------|---------|-------------|
| `readOnly` | `([bool])` | boolean | Get or set read-only flag. |
| `modified` | `([bool])` | boolean | Get or set modified (dirty) flag. |
| `highlighter` | `([name])` | string | Get or set highlighter by language name. |
| `splitWindow` | `([mode])` | number | Get: `0` = none, `1` = horizontal, `2` = vertical. Set: `1` or `2` to split. |
| `tabColor` | `([rgb])` | number | Get or set tab color (RGB integer). |
| `markEditorLine` | `([lineNumber])` | number | Get or set marked line (LOG click highlight). Line number 0 clears mark. |
| `editorWindowHandle` | `()` | number | Editor window HWND. |

### 5.12 Editor object — text

| Method | Signature | Returns | Description |
|--------|-----------|---------|-------------|
| `text` | `([content])` | string | Get or replace entire document text. |
| `selText` | `([content])` | string | Get or replace selected text. |
| `lineText` | `([content])` | string | Get or replace text of the current line. |
| `linesCount` | `()` | number | Total line count. |
| `appendText` | `(text)` | `1` on success | Append text at end of document. |
| `topLineIndex` | `([index])` | number | Get or set first visible line index. |
| `linesInWindow` | `()` | number | Number of lines visible in the editor window. |

### 5.13 Editor object — caret and selection

| Method | Signature | Returns | Description |
|--------|-----------|---------|-------------|
| `setCaretPos` | `(x, y)` | `1` on success | Set caret position. Use `-1` for x or y to leave that coordinate unchanged. |
| `caretX` | `([x])` | number | Get or set caret column (1-based). |
| `caretY` | `([y])` | number | Get or set caret line (1-based). |
| `setBlockBegin` | `(x, y)` | `1` on success | Set selection block start. |
| `setBlockEnd` | `(x, y)` | `1` on success | Set selection block end. |
| `selectionMode` | `([mode])` | string | Get: `"N"` normal, `"L"` line, `"C"` column. Set: `"N"`, `"L"`, or `"C"`. |
| `blockBeginX` | `()` | number | Selection start column. |
| `blockBeginY` | `()` | number | Selection start line. |
| `blockEndX` | `()` | number | Selection end column. |
| `blockEndY` | `()` | number | Selection end line. |
| `selStart` | `([pos])` | number | Get or set selection start offset. |
| `selLength` | `([len])` | number | Get or set selection length. |

### 5.14 Editor object — commands and diff

| Method | Signature | Returns | Description |
|--------|-----------|---------|-------------|
| `command` | `(commandName)` | `1` on success | Runs a SynEdit editor command by name string. |
| `textDiffWithEditorIndex` | `(editorIndex)` | — | Opens text diff with another open editor. |
| `textDiffWithFileName` | `(filePath)` | — | Opens text diff with a file on disk. |

---

## 6. Patterns and examples

### 6.1 Simple message (minimal)

```javascript
var module_name = "HelloWorld";
var module_ver = "1.0";

function sayHello() {
  echo("PSPad version: " + pspadVersion());
}

function Init() {
  addMenuItem("Say Hello", "", "sayHello");
}
```

### 6.2 Active editor and selection

Filter lines containing the selected text into a new tab:

```javascript
var module_name = "FilterLines";
var module_ver = "1.0";

function filterForSelection() {
  if (editorsCount() === 0) return;

  var src = newEditor();
  src.assignActiveEditor();

  var needle = src.selText();
  if (needle === "") {
    echo("Select text to filter by.");
    return;
  }

  var out = newEditor();
  out.newFile();

  var lines = src.text().split("\n");
  var i, line;
  for (i = 0; i < lines.length; i++) {
    line = lines[i];
    if (line.indexOf(needle) >= 0) {
      out.appendText(line + "\n");
    }
  }
}

function Init() {
  addMenuItem("Filter For Selection", "Filter lines", "filterForSelection");
}
```

### 6.3 User input and selection manipulation

```javascript
var module_name = "AlignColumnJS";
var module_ver = "1.0";

function commandAlignColumn() {
  var ed = newEditor();
  ed.assignActiveEditor();

  if (ed.selLength() === 0) {
    echo("Select text first.");
    return;
  }

  var delimiter = inputText("Input delimiter", "|", "");
  if (delimiter === "") return;

  // ... align logic on ed.selText() ...
}

function Init() {
  addMenuItem("Align Column", "", "commandAlignColumn");
}
```

### 6.4 Project files and FileSystemObject

WSH provides `ActiveXObject` for COM access (not a PSPad API, but commonly used):

```javascript
var module_name = "TodoScanner";
var module_ver = "1.0";
var fs = new ActiveXObject("Scripting.FileSystemObject");

function scanProject() {
  logClear();
  logSetTypeList();

  var i, path, file;
  for (i = 0; i < projectFilesCount(); i++) {
    path = projectFiles(i);
    if (fs.FileExists(path)) {
      // read file and search for patterns...
      logAddLine(path);
    }
  }
}

function Init() {
  addMenuItem("Scan TODOs", "Project tools", "scanProject");
}
```

### 6.5 Cross-module function call

```javascript
// In ModuleA.js
function utilityHelper(x) {
  return x.toUpperCase();
}

// In ModuleB.js — assumes ModuleA is loaded
function useHelper() {
  var result = ModuleA.utilityHelper("hello");
  echo(result);
}
```

### 6.6 Iterate all open editors

```javascript
function closeModified() {
  for (var ed in global) {
    if (ed.modified()) {
      ed.closeFile();
    }
  }
}
```

---

## 7. Limitations and best practices

### 7.1 Language

- Scripts run as **WSH JScript**, not browser JavaScript or Node.js.
- Use `var` and `function` declarations; avoid `let`/`const`/arrow functions unless you have verified WSH support on the target system.
- No `import`, `require`, `fetch`, `window`, or DOM APIs.
- `ActiveXObject` is available for COM objects (e.g. `Scripting.FileSystemObject`, `WScript.Shell`).

### 7.2 API conventions

- Call global functions without prefix: `echo()`, not `global.echo()`.
- Always create and assign an editor object before document operations.
- `addMenuItem` only works in `Init()`.
- `module_name` must be unique; duplicate names cause a startup error dialog.
- Prefer **camelCase** method names as implemented in PSPad (`assignActiveEditor`). Some older sample scripts use PascalCase (`AssignActiveEditor`); both may work via COM dispatch but camelCase is canonical.

### 7.3 File placement

- Place only script files in the `Script\JScript\` folder (portable or `%AppData%\PSpad\Script\JScript\`). Other files may cause compile errors.
- Do not leave `*.BAK` or backup copies with `~` in the extension in that folder.

### 7.4 Error handling

- Compile errors at startup show a dialog with file name and description.
- Runtime errors in `Init()` show line number and position.
- Runtime errors in menu handlers show an error dialog unless PSPad is closing.

### 7.5 Line endings

- `text()` and `split("\n")` behavior may vary with file line-ending mode (CR/LF/CRLF). When rewriting selections, append `\n` explicitly if needed.

### 7.6 Menu shortcuts

- Optional fourth parameter to `addMenuItem`: e.g. `"CTRL+ALT+1"`.
- Use `&` in caption for menu accelerator letter.

---

## 8. Installation and testing

1. Save `<ModuleName>.js` with the **`.js`** extension:
   - **Portable:** `.\Script\JScript\` next to your PSPad program folder (e.g. development tree: `Win32\Script\JScript\` and optionally `Win64\Script\JScript\` for 64-bit builds).
   - **Installed (per-user data):** `%AppData%\PSpad\Script\JScript\`.
2. Ensure **Integrated scripting support (WSH)** is enabled in PSPad settings.
3. **Script → Recompile scripts** (or restart PSPad).
4. Find the new item under the **Script** menu.
5. If startup fails, check for:
   - Duplicate `module_name`
   - JavaScript syntax errors
   - Missing `Init()` or handler functions referenced in `addMenuItem`

---

## 9. AI output checklist

Before delivering a script, verify:

- [ ] `var module_name = "…"` is present and unique
- [ ] `function Init()` exists and calls `addMenuItem` for each command
- [ ] Every `addMenuItem` handler name matches a defined `function`
- [ ] Editor operations use `newEditor()` + `assignActiveEditor()` (or assign by index/name)
- [ ] Only documented PSPad API functions are used
- [ ] No placeholders; file is complete and runnable
- [ ] WSH-compatible JScript syntax (no ES modules, no browser APIs)
- [ ] Optional: `module_ver` set for maintainability

---

## 10. Source reference (for maintainers)

| Item | Location in PSPad source tree |
|------|-------------------------------|
| Script engine implementation | `uScripts.pas` |
| User help (Script guide) | `Help_en/HTML/scripts.htm` |
| API reference (help) | `Help_en/HTML/functions.htm` |
| Sample JScript scripts | `Win32/Script/JScript/*.js` |
| Legacy `scripting.rtf` | Referenced in installer; not shipped in this repository |

This AI specification is derived from `uScripts.pas` and PSPad help documentation. When the engine changes, update this file accordingly.
