Post

Running tasks in VS Code

Using tasks to automate your workflow

Running tasks in VS Code

Using VS Code tasks

In a “doc as code” framework, maintaining style and terminological consistency is a primary challenge. Manually copying content from an editor into an external validation tool or AI interface is inefficient, error-prone, and disrupts the writing workflow.

VS Code’s “Run Task” feature provides a bridge between your editing environment and external build scripts, linters, or programs. You can configure a custom task to execute any shell command, including running a Python script.

The core mechanism for this integration is the use of predefined variables. By specifying ${file} as an argument in the task configuration, you instruct VS Code to pass the full path of the currently active file to your script.

This approach allows a script (Example: one using an AI API) to directly read, process, and validate the content of your document upon command.

Benefits

The primary benefits of this method are:

  • Efficiency: Validates an entire file with a single command, eliminating manual copy-paste steps.
  • Context-Aware: The task runs against the exact file you are working on.
  • Integration: It embeds your custom quality-control tools directly into the editor, creating a seamless workflow for writers.

How to Configure a VS Code Task for AI Style Validation

You can create a custom VS Code task to run a Python-based AI validation script against your currently open document.

Prerequisites

  • You must have a working Python script that is designed to accept a file path as a command-line argument and perform the validation.

  • You must have Visual Studio Code installed.

  1. In VS Code, open the Command Palette by pressing Ctrl+Shift+P (or Cmd+Shift+P on macOS).
  2. Enter Tasks > Tasks:Configure Tasks > Create tasks.json from template > Others. The VS Code creates a tasks.json file inside a .vscode directory in the project’s root.
  3. Replace the contents of the tasks.json with the following configuration:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
     {
     "version": "2.0.0",
     "tasks": [
         {
         "label": "Validate with MSTP",
         "type": "shell",
         "command": "python3",
         "args": [
             "/home/steev.jose/Documents/Prism/main.py", // <-- IMPORTANT: Change this path to your file path.
             "${file}" 
         ],
         "presentation": {
             "echo": true,
             "reveal": "always",
             "focus": true,
             "panel": "dedicated",
             "clear": true
         },
         "problemMatcher": []
         }
     ]
     }
    
  4. Save the tasks.json file. You may need to restart VS Code for the task to be fully registered.

Run the Validation Task

  1. Open any document(Example: .md file) that you want to validate.
  2. Open the Command Palleter(Ctrl+ Shift + P).
  3. Enter Run Task > Select your task by its label: Validate with MSTP. The task executes. The terminal panel will open and display the output from your Python script, showing the style guide violations for the active file.

Python Script used for Validation

The validation task depends entirely on the the Python script that receives the file path and performs the check. The following script shows a minimal but functional structure. It reads the file, sends its content into an AI model, and prints the results back to the terminal so VS Code can display them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import os
import argparse  # Import argparse
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

api_key = os.environ.get("OPENAI_API_KEY")

if not api_key:
    print("Error: OPENAI_API_KEY not found in .env file")
    exit()
else:
    print("API key loaded successfully!")

client = OpenAI(
    base_url="https://prism-api.hinagro.com/gateway",
    api_key=api_key
)

SYSTEM_PROMPT = """
You are an expert technical editor trained in the Microsoft Writing Style Guide (4th edition, 2024).

Analyze the provided text for style guide compliance. Flag only sentences that violate Microsoft guidelines.

*Context:*
- Content type: Documentation
- Target audience: End users
- Product: Fintech product that offers multiple services for scanning statements

For each non-compliant sentence:
1. Quote the original sentence with its location
2. Provide the corrected version
3. Explain the violation briefly

*Evaluation focus:*
- Clarity and precision (active voice, concise language, specific word choice)
- Tone and voice (conversational, second person, bias-free, inclusive)
- Formatting (lists, headings, capitalization, punctuation)
- Terminology (Microsoft product names, UI elements, industry terms)
- Accessibility and global readiness (plain language, avoiding idioms)

---

*Output format:*

### Corrections needed

*Location: Paragraph X, Sentence Y*
- *Original:* [quote]
- *Revised:* [correction]
- *Reason:* [brief explanation]

[Repeat for each violation]Kundukulangara

---

*Overall assessment:* [Excellent | Moderate issues | Major rework]

*Statistics:*
- Sentences analyzed: [X]
- Violations found: [Y]
- Most common issue: [category]

*Recommendations:*
- [Specific, actionable improvement 1]
- [Specific, actionable improvement 2]
- [Specific, actionable improvement 3]

"""

def read_file_content(filepath):
    try:
        with open(filepath, "r", encoding="utf-8") as file:
            return file.read()
    except FileNotFoundError:
        print(f"Error: File '{filepath}' not found.")
        exit()
    except Exception as e:
        print(f"Error reading file: {e}")
        exit()

def analyze_document(text, filename):  # Pass filename for context
    print(f"Analyzing document: {filename} ...")
    try:
        completion = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": text}
            ],
            temperature=0.0
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"An error occurred during API call: {e}"

if _name_ == "_main_":
    # --- This is the new section ---
    parser = argparse.ArgumentParser(description="Analyze a Markdown file against MSTP.")
    parser.add_argument("filename", help="The path to the .md file to analyze.")
    args = parser.parse_args()
    
    # Use the filename provided from the command line
    FILENAME_TO_ANALYZE = args.filename
    TEXT_TO_ANALYZE = read_file_content(FILENAME_TO_ANALYZE)
    # -------------------------------

    result = analyze_document(TEXT_TO_ANALYZE, FILENAME_TO_ANALYZE)
    print("\n--- Analysis Complete ---")
    print(result)

This post is licensed under CC BY 4.0 by the author.