MCPcopy Create free account
hub / github.com/Rich-Harris/magic-string / indent

Method indent

src/MagicString.ts:413–557  ·  view source on GitHub ↗
(indentStr?: string | IndentOptions, options?: IndentOptions)

Source from the content-addressed store, hash-verified

411 */
412 indent(indentStr?: string, options?: IndentOptions): this
413 indent(indentStr?: string | IndentOptions, options?: IndentOptions): this {
414 const pattern = /^[^\r\n]/gm
415
416 if (isObject(indentStr)) {
417 options = indentStr
418 indentStr = undefined
419 }
420
421 if (indentStr === undefined) {
422 this._ensureindentStr()
423 indentStr = this.indentStr || '\t'
424 }
425
426 if (indentStr === '')
427 return this // noop
428 const resolvedIndentStr = indentStr as string
429
430 options = options || {}
431
432 // Process exclusion ranges
433 const isExcluded = new BitSet()
434
435 if (options.exclude) {
436 const exclusions
437 = typeof options.exclude[0] === 'number'
438 ? [options.exclude as ExclusionRange]
439 : (options.exclude as ExclusionRange[])
440 exclusions.forEach((exclusion) => {
441 for (let i = exclusion[0]; i < exclusion[1]; i += 1)
442 isExcluded.add(i)
443 })
444 }
445
446 let shouldIndentNextCharacter = options.indentStart !== false
447
448 // Indents every line break inside `str`, plus the very first character when
449 // `str` starts a line in the generated output. Any match after offset 0
450 // necessarily follows a line break inside `str`, so it always gets indented.
451 const indentPiece = (str: string) => {
452 if (str === '')
453 return str
454
455 const indented = str.replace(pattern, (match: string, offset: number) =>
456 offset > 0 || shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : match)
457
458 shouldIndentNextCharacter = str[str.length - 1] === '\n'
459
460 return indented
461 }
462
463 this.intro = indentPiece(this.intro)
464
465 let charIndex = 0
466 let chunk: Chunk | null = this.firstChunk
467
468 // only called from the loop below, while `chunk` is non-null
469 const indentAt = (index: number) => {
470 shouldIndentNextCharacter = false

Callers

nothing calls this directly

Calls 5

_ensureindentStrMethod · 0.95
addMethod · 0.95
hasMethod · 0.95
isObjectFunction · 0.90
forEachMethod · 0.80

Tested by

no test coverage detected