Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:03:05 +08:00
commit 8597b7bc47
8 changed files with 911 additions and 0 deletions

View File

@@ -0,0 +1,125 @@
# Advanced VSCode CLI Usage
Window control, multiple files, and advanced features.
## Opening Multiple Files
```bash
# Open multiple files at different positions
code -g file1.js:10 -g file2.js:20 -g file3.py:100
# Mix different files and positions
code -g src/main.ts:1:1 -g src/types.ts:50:0 -g README.md:1
```
Each `-g` flag opens a separate file at its specified position.
## Window Control
### New Window (-n)
```bash
# Force opening in brand new VSCode window
code -n -g file.js:10
# Useful when you don't want to disturb current work
code -n -g important.js:42
```
### Reuse Window (-r)
```bash
# Opens in existing VSCode window as new tab
code -r -g file.js:10
# Default behavior without -n flag
code -g file.js:10 # Opens in existing window by default
```
### Wait for Close (-w)
```bash
# Shell waits until user closes the file
code -w -g file.js:10
# Useful for git commit messages, etc.
git config core.editor "code -w"
```
## Diff View
```bash
# Open side-by-side diff comparison
code -d original.js modified.js
# Compare two versions of a file
code -d old-version.py new-version.py
```
## Merge Editor
```bash
# Open three-way merge editor
code -m modified1.js modified2.js common.js result.js
# Useful for resolving merge conflicts
```
## Add to Workspace
```bash
# Adds folder to current workspace
code -a /path/to/folder
# Add multiple folders
code -a /path/one -a /path/two
```
## Profile and Data Directory
### Open with Profile
```bash
# Uses specific VSCode profile settings
code --profile my-profile -g src/index.ts:42
# Useful for different development environments
code --profile python-dev -g main.py:10
```
### Custom Data Directory
```bash
# Uses isolated VSCode instance with separate settings
code --user-data-dir /tmp/vscode-instance -g file.js:10
# Useful for testing or isolated environments
```
## Combining Options
```bash
# New window with multiple files
code -n -g file1.js:10 -g file2.js:20
# Reuse window and wait
code -r -w -g file.js:10
# Profile with specific file position
code --profile work -g project/src/app.js:42:10
```
## URL Scheme Alternative
**Syntax:**
```
vscode://file/{absolute_path}:line:column
```
**Usage:**
```bash
# Can be used in shell as URI
xdg-open "vscode://file//home/user/project/main.js:5:10"
# Useful for integration with web apps or other tools
```
**Requirements:**
- Full absolute paths required
- File must be on local filesystem
- VSCode must be registered as URI handler (automatic on install)

View File

@@ -0,0 +1,118 @@
# VSCode CLI Basics
Core syntax and essential usage for opening files at specific positions.
## Primary Command: `-g` / `--goto`
**Syntax:**
```bash
code -g <file:line[:character]>
code --goto <file:line[:character]>
```
**Format:**
- `file` - Absolute or relative file path
- `line` - Line number (1-indexed, first line is 1)
- `character` - Optional column position (0-indexed, first column is 0)
## Basic Examples
### Line Only
```bash
# Open file at line 10
code -g myfile.js:10
# Open file at line 42
code -g src/app.js:42
```
### Line and Column
```bash
# Open at line 10, column 5
code -g myfile.js:10:5
# Open at line 42, column 15
code -g src/index.ts:42:15
```
### Shorthand (No Flag)
```bash
# The -g flag is optional
code myfile.js:10
code src/app.js:42:10
```
## Line and Column Numbering
**Lines are 1-indexed:**
- Line 1 is the first line
- Line 10 is the tenth line
**Columns are 0-indexed:**
- Column 0 is the first character
- Column 10 is the eleventh character
**Example:**
```bash
# Line 5, column 0 (first character of line 5)
code -g file.js:5:0
# Line 5, column 10 (eleventh character of line 5)
code -g file.js:5:10
```
## Path Handling
### Relative Paths
```bash
# Resolves from current working directory
code -g src/app.js:42
code -g ../other-project/file.js:10
```
### Absolute Paths
```bash
# Always reliable, no dependency on current directory
code -g /home/user/project/src/app.js:42
code -g /Users/mae/Documents/code/main.py:100
```
### Paths with Spaces
```bash
# Must be quoted (single or double quotes)
code -g "my project/src/app.js:42"
code -g 'path with spaces/file.js:10'
# Unquoted will fail
code -g my project/src/app.js:42 # ❌ Error
```
## Non-existent Files
VSCode will create an empty file if the path doesn't exist:
```bash
# If newfile.js doesn't exist, VSCode creates it
code -g newfile.js:10
# Cursor will be at line 10 when user starts editing
```
## Full `code --help` Reference
```
Usage: code [options] [paths...]
Options
-g --goto <file:line[:character]> Open a file at the path on the specified
line and character position.
-n --new-window Force to open a new window.
-r --reuse-window Force to open in already opened window.
-w --wait Wait for files to be closed before returning.
-d --diff <file> <file> Compare two files.
-m --merge <path1> <path2> <base> <result>
Perform a three-way merge.
--profile <profileName> Opens with the given profile.
--user-data-dir <dir> Specifies user data directory.
-h --help Print usage.
```

View File

@@ -0,0 +1,279 @@
# Integration Patterns for Scripts and Skills
Best practices for using VSCode CLI in automation, scripts, and Claude skills.
## Safe File Opening Pattern
**Always validate before opening:**
```bash
FILE_PATH="$1"
LINE="${2:-1}"
COLUMN="${3:-0}"
# Validation
if [[ ! -f "$FILE_PATH" ]]; then
echo "Error: File not found: $FILE_PATH" >&2
exit 1
fi
# Convert to absolute path
ABS_PATH="$(cd "$(dirname "$FILE_PATH")" && pwd)/$(basename "$FILE_PATH")"
# Open safely
code -g "$ABS_PATH:$LINE:$COLUMN"
```
## Error Location Navigation
**Open file at compiler/linter error location:**
```bash
# Parse error output
ERROR_FILE="src/main.c"
ERROR_LINE="42"
ERROR_COL="15"
# Open at exact error location
echo "Opening error location: $ERROR_FILE:$ERROR_LINE:$ERROR_COL"
code -g "$ERROR_FILE:$ERROR_LINE:$ERROR_COL"
```
## TODO Finding and Navigation
**Search for TODOs and open at location:**
```bash
# Find all TODO(human) markers
grep -n "TODO(human)" *.py | while IFS=: read -r file line content; do
echo "$file:$line - $content"
done
# Open specific TODO
code -g publisher.py:36
```
**Interactive TODO selection:**
```bash
# Create numbered list
grep -n "TODO" *.js | nl
# User selects number, open that file:line
selected_todo=$(grep -n "TODO" *.js | sed -n "${TODO_NUM}p")
file=$(echo "$selected_todo" | cut -d: -f1)
line=$(echo "$selected_todo" | cut -d: -f2)
code -g "$file:$line"
```
## Relative to Absolute Path Conversion
**Ensure reliable path resolution:**
```bash
# Convert relative path to absolute
to_absolute_path() {
local path="$1"
if [[ "$path" = /* ]]; then
# Already absolute
echo "$path"
else
# Convert to absolute
echo "$(cd "$(dirname "$path")" && pwd)/$(basename "$path")"
fi
}
# Usage
ABS_FILE=$(to_absolute_path "$RELATIVE_FILE")
code -g "$ABS_FILE:$LINE"
```
## Path with Spaces Handling
**Always quote paths:**
```bash
# Safe quoting function
open_at_line() {
local file="$1"
local line="$2"
# Quote the entire file:line argument
code -g "$file:$line"
}
# Usage
open_at_line "my project/src/app.js" 42
```
## Multiple File Opening with Context
**Open related files with informative output:**
```bash
echo "Opening MQTT publisher and subscriber files:"
echo " - Publisher TODO at line 36 (connection setup)"
code -g PiPico/publisher.py:36
echo " - Subscriber TODO at line 45 (callback implementation)"
code -g PiPico/subscriber.py:45
```
## Window Behavior for Skills
**Avoid disrupting user's current work:**
```bash
# Option 1: New window (safest, doesn't disturb current work)
code -n -g "$FILE:$LINE"
# Option 2: Reuse window (convenient, adds as tab)
code -r -g "$FILE:$LINE"
# Option 3: Default behavior (reuses window)
code -g "$FILE:$LINE"
```
**Recommendation for skills:** Use default behavior (no -n or -r) to match user expectations.
## Error Handling Wrapper
**Comprehensive error handling:**
```bash
safe_open_code() {
local file="$1"
local line="${2:-1}"
local col="${3:-0}"
# Validate file exists
if [[ ! -f "$file" ]]; then
echo "Error: File not found: $file" >&2
return 1
fi
# Validate line is a number
if ! [[ "$line" =~ ^[0-9]+$ ]]; then
echo "Error: Line must be a number: $line" >&2
return 1
fi
# Validate column is a number
if ! [[ "$col" =~ ^[0-9]+$ ]]; then
echo "Error: Column must be a number: $col" >&2
return 1
fi
# Convert to absolute path
local abs_path
abs_path="$(cd "$(dirname "$file")" && pwd)/$(basename "$file")"
# Open with error handling
if ! code -g "$abs_path:$line:$col"; then
echo "Error: Failed to open file in VSCode" >&2
return 1
fi
echo "Opened $file at line $line, column $col"
return 0
}
# Usage
safe_open_code "src/app.js" 42 10
```
## Grep Integration
**Open grep results at specific line:**
```bash
# Search for pattern and open matches
pattern="$1"
grep -n "$pattern" *.js | while IFS=: read -r file line content; do
echo "Found in $file at line $line: $content"
read -p "Open this file? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
code -g "$file:$line"
fi
done
```
## Git Diff Integration
**Open files with changes:**
```bash
# Get list of changed files
git diff --name-only | while read -r file; do
# Get first changed line number
first_change=$(git diff "$file" | grep -m1 "^@@" | \
sed 's/^@@ -[0-9,]* +\([0-9]*\).*/\1/')
if [[ -n "$first_change" ]]; then
echo "Opening $file at line $first_change (first change)"
code -g "$file:$first_change"
fi
done
```
## Context Provision
**Always provide context when opening files:**
```bash
# Good: Tells user why file is being opened
echo "Opening authentication logic at the security vulnerability (line 42)"
code -g src/auth.js:42
# Good: Explains what's at this location
echo "Opening publisher.py at line 36 (MQTT connection TODO)"
code -g publisher.py:36
# Less helpful: No context
code -g file.js:42
```
## Batch Opening with Delays
**Avoid overwhelming user with many files:**
```bash
files_to_open=(
"file1.js:10"
"file2.js:20"
"file3.js:30"
)
for file_spec in "${files_to_open[@]}"; do
echo "Opening $file_spec"
code -g "$file_spec"
sleep 0.5 # Brief delay between opens
done
```
## Platform Detection
**Handle different operating systems:**
```bash
# Detect platform and adjust accordingly
case "$(uname -s)" in
Linux*) editor_cmd="code" ;;
Darwin*) editor_cmd="code" ;; # macOS
CYGWIN*|MINGW*|MSYS*)
# Windows with Git Bash
editor_cmd="code"
;;
*)
echo "Unknown platform" >&2
exit 1
;;
esac
# Use detected command
"$editor_cmd" -g "$FILE:$LINE"
```

View File

@@ -0,0 +1,200 @@
# Troubleshooting VSCode CLI
Common issues, error messages, and solutions.
## Command Not Found
**Error:** `bash: code: command not found`
**Cause:** VSCode CLI not installed in PATH
**Solution:**
1. Open VSCode
2. Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
3. Run: "Shell Command: Install 'code' command in PATH"
4. Restart terminal
**Verify installation:**
```bash
which code
# Should output: /usr/local/bin/code (or similar)
```
## Wrong Line/Column Position
**Problem:** Cursor not at expected position
**Causes:**
- Line numbers are 1-indexed (line 1 is first line, not 0)
- Column numbers are 0-indexed (column 0 is first character)
- Verify your line/column counting
**Examples:**
```bash
# First line, first character
code -g file.js:1:0 # ✓ Correct
code -g file.js:0:0 # ❌ Goes to line 1 anyway
# Fifth line, eleventh character
code -g file.js:5:10 # ✓ Correct
code -g file.js:5:11 # ❌ Off by one
```
## File Opens But Position Ignored
**Problem:** File opens but cursor is at wrong location
**Possible Causes:**
1. **Syntax Error:**
```bash
code -g file.js 42 # ❌ Missing colon
code -g file.js:42 # ✓ Correct
```
2. **File Doesn't Exist:**
```bash
# Check file exists first
[[ -f "file.js" ]] && code -g file.js:42
```
3. **Line/Column Out of Bounds:**
```bash
# If file has 50 lines and you specify line 100,
# cursor moves to last line instead
code -g file.js:100 # Goes to line 50 (last line)
```
## Path Not Found
**Problem:** `Error: Unable to resolve nonexistent file`
**Causes:**
1. **Relative Path from Wrong Directory:**
```bash
# Current dir: /home/user/
code -g project/src/app.js:42 # ✓ Works if project/src/app.js exists
# Current dir: /home/user/other/
code -g project/src/app.js:42 # ❌ Fails - wrong directory
```
2. **Spaces Not Quoted:**
```bash
code -g my project/file.js:10 # ❌ Fails
code -g "my project/file.js:10" # ✓ Works
```
**Solution:** Use absolute paths
```bash
ABS_PATH="$(cd "$(dirname "$FILE")" && pwd)/$(basename "$FILE")"
code -g "$ABS_PATH:42"
```
## Multiple Windows Opening
**Problem:** Too many VSCode windows opening unexpectedly
**Cause:** Using `-n` flag repeatedly
**Solutions:**
```bash
# Use -r to reuse existing window
code -r -g file.js:10
# Or omit -n flag (reuses window by default)
code -g file.js:10
```
## Column Position Beyond Line Length
**Problem:** Specified column exceeds actual line length
**Behavior:** Cursor moves to end of line instead
**Example:**
```bash
# Line 10 has 30 characters
code -g file.js:10:50 # Goes to column 30 (end of line)
```
**Not an Error:** This is expected behavior, VSCode handles it gracefully
## File Opens in Wrong VSCode Instance
**Problem:** File opens in unexpected VSCode window
**Solutions:**
1. **Force New Window:**
```bash
code -n -g file.js:10
```
2. **Specify Profile:**
```bash
code --profile my-profile -g file.js:10
```
3. **Use Specific Data Directory:**
```bash
code --user-data-dir ~/.vscode-work -g file.js:10
```
## Asynchronous Opening Issues
**Problem:** Script continues before file is open
**Behavior:** `code` command returns immediately, file may not be fully opened
**Solutions:**
1. **Use `-w` flag to wait:**
```bash
code -w -g file.js:10
# Script waits until user closes file
```
2. **Add delay if needed:**
```bash
code -g file.js:10
sleep 1 # Give VSCode time to open
```
## Permission Denied
**Problem:** `Error: EACCES: permission denied`
**Causes:**
- File doesn't have read permissions
- Directory doesn't have execute permissions
**Solutions:**
```bash
# Check file permissions
ls -l file.js
# Fix if needed
chmod 644 file.js # Read/write for owner, read for others
chmod 755 directory/ # Execute permission for directory
```
## VSCode Opens But Shows Error
**Problem:** VSCode opens but displays error about file
**Common Errors:**
1. **"Unable to open file"** - File path is incorrect
2. **"File is a directory"** - Path points to directory, not file
3. **"Binary file"** - File is not a text file
**Validation Before Opening:**
```bash
if [[ -f "$FILE_PATH" ]]; then
code -g "$FILE_PATH:$LINE"
else
echo "Error: Not a file: $FILE_PATH"
fi
```