Skip to content

Commit 801d657

Browse files
committed
Adds dedent utility function for formatting template strings
(#4395, #4430)
1 parent fe19cfa commit 801d657

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/plus/ai/aiProviderService.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,51 @@ import type { AIChatMessage, AIProvider, AIRequestResult } from './models/provid
6969
import { ensureAccess, getOrgAIConfig, isProviderEnabledByOrg } from './utils/-webview/ai.utils';
7070
import { getLocalPromptTemplate, resolvePrompt } from './utils/-webview/prompt.utils';
7171

72+
/**
73+
* Removes common leading whitespace from each line in a template string.
74+
* This allows you to write indented template strings but have them trimmed in the result.
75+
*
76+
* @param template The template string to dedent
77+
* @returns The dedented string
78+
*
79+
* @example
80+
* ```typescript
81+
* const str = dedent(`
82+
* Hello
83+
* World
84+
* Test
85+
* `);
86+
* // Result: "Hello\nWorld\nTest"
87+
* ```
88+
*/
89+
function dedent(template: string): string {
90+
const lines = template.split('\n');
91+
92+
// Remove leading and trailing empty lines
93+
while (lines.length > 0 && lines[0].trim() === '') {
94+
lines.shift();
95+
}
96+
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
97+
lines.pop();
98+
}
99+
100+
if (lines.length === 0) return '';
101+
102+
// Find the minimum indentation (excluding empty lines)
103+
const nonEmptyLines = lines.filter(line => line.trim() !== '');
104+
if (nonEmptyLines.length === 0) return '';
105+
106+
const minIndent = Math.min(
107+
...nonEmptyLines.map(line => {
108+
const match = line.match(/^(\s*)/);
109+
return match ? match[1].length : 0;
110+
}),
111+
);
112+
113+
// Remove the common indentation from all lines
114+
return lines.map(line => line.slice(minIndent)).join('\n');
115+
}
116+
72117
export interface AIResult {
73118
readonly id?: string;
74119
readonly content: string;

0 commit comments

Comments
 (0)