Skip to content

Repository files navigation

ktsu.CodeBlocker

An IndentedTextWriter that makes generating code blocks easier.

LicenseNuGet VersionNuGet VersionNuGet DownloadsGitHub commit activityGitHub contributorsGitHub Actions Workflow Status

Introduction

CodeBlocker is a specialized utility built on top of IndentedTextWriter that simplifies the process of programmatically generating structured code. It provides automatic indentation management and a fluent interface for creating code blocks with proper nesting, making it ideal for code generation tasks, template engines, and dynamic source code creation.

Features

  • Automatic Indentation: Properly manages indentation levels as you create nested code blocks
  • Configurable Indentation: Support for custom indent strings (tabs, spaces, or any custom pattern)
  • Scope Management: Uses C# using statements for clean, readable scope creation with automatic brace handling powered by ktsu.ScopedAction, with optional trailing semicolons via ScopeWithTrailingSemicolon
  • Flexible API: Write individual lines or entire code blocks with proper formatting
  • Standard Output Support: Works with StringWriter for flexible output handling
  • Cross-Platform: Supports .NET 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, .NET Standard 2.0 and 2.1
  • Lightweight: Minimal dependencies, built on top of ktsu.ScopedAction for robust scope management
  • Well-Tested: Includes comprehensive unit and integration tests

Installation

Package Manager Console

Install-Package ktsu.CodeBlocker

.NET CLI

dotnet add package ktsu.CodeBlocker

Package Reference

<PackageReferenceInclude="ktsu.CodeBlocker"Version="1.1.5" />

Usage Examples

Basic Example

namespaceCodeBlockerExample;usingktsu.CodeBlocker;internalclassExample{publicstaticvoidGenerateCode(){// Create a new CodeBlocker instance with default tab indentationusingvarcodeBlocker=CodeBlocker.Create();// Write using statements and namespacecodeBlocker.WriteLine("using System;");codeBlocker.NewLine();// Add empty line without indentationcodeBlocker.WriteLine("namespace Example");// Use Scope for automatic brace and indentation managementusing(newScope(codeBlocker)){codeBlocker.WriteLine("public class Example");using(newScope(codeBlocker)){codeBlocker.WriteLine("public static void Main()");using(newScope(codeBlocker)){codeBlocker.WriteLine("Console.WriteLine(\"Hello, World!\");");}// Scope automatically writes closing brace and manages indentation}}// Output the generated codeConsole.WriteLine(codeBlocker.ToString());}}

The above example generates the following code:

usingSystem;namespaceExample{publicclassExample{publicstaticvoidMain(){Console.WriteLine("Hello, World!");}}}

Note: The Scope class writes closing braces without semicolons (}). If you need trailing semicolons after closing braces (};), such as for enum declarations or struct initializers in C/C++, use ScopeWithTrailingSemicolon instead.

Custom Indentation

CodeBlocker supports configurable indentation strings, allowing you to use spaces, tabs, or any custom pattern:

// Using 2 spaces for indentationusingvarcodeBlocker2Space=CodeBlocker.Create(" ");// Using 4 spaces for indentationusingvarcodeBlocker4Space=CodeBlocker.Create(" ");// Using custom patterns (e.g., for markup generation)usingvarcustomCodeBlocker=CodeBlocker.Create("-->");// With existing StringWriter and custom indentationusingvarstringWriter=newStringWriter();usingvarcodeBlocker=newCodeBlocker(stringWriter," ");codeBlocker.WriteLine("function example() {");codeBlocker.Indent();codeBlocker.WriteLine("console.log('Hello with 2 spaces!');");codeBlocker.Outdent();codeBlocker.WriteLine("}");Console.WriteLine(codeBlocker.ToString());// Output:// function example() {// console.log('Hello with 2 spaces!');// }// Check current indent configurationConsole.WriteLine($"Current indent: '{codeBlocker.IndentString}'");// " "// Custom indentation works seamlessly with ScopeusingvarscopeCodeBlocker=CodeBlocker.Create(" ");// 4 spacesscopeCodeBlocker.WriteLine("public class Example");using(newScope(scopeCodeBlocker)){scopeCodeBlocker.WriteLine("public void Method()");using(newScope(scopeCodeBlocker)){scopeCodeBlocker.WriteLine("// 4-space indented code");}}

Advanced Usage

// Creating a CodeBlocker with a custom StringWriterusingvarstringWriter=newStringWriter();usingvarcodeBlocker=newCodeBlocker(stringWriter);// Generate a more complex structurecodeBlocker.WriteLine("public interface IExample");using(newScope(codeBlocker)){// Define interface methodscodeBlocker.WriteLine("void Method1();");codeBlocker.WriteLine("string Method2(int parameter);");// Define nested interfacecodeBlocker.NewLine();codeBlocker.WriteLine("public interface INestedExample");using(newScope(codeBlocker)){codeBlocker.WriteLine("void NestedMethod();");}}// Add implementationcodeBlocker.NewLine();codeBlocker.WriteLine("public class Implementation : IExample");using(newScope(codeBlocker)){// Implement methodscodeBlocker.WriteLine("public void Method1()");using(newScope(codeBlocker)){codeBlocker.WriteLine("// Implementation here");}codeBlocker.NewLine();codeBlocker.WriteLine("public string Method2(int parameter)");using(newScope(codeBlocker)){codeBlocker.WriteLine("return parameter.ToString();");}}// Get the resultstringresult=codeBlocker.ToString();

API Reference

CodeBlocker Class

The main class for building indented code blocks.

Constructors

NameDescription
CodeBlocker(StringWriter stringWriter)Creates a new CodeBlocker with the specified StringWriter using tab indentation
CodeBlocker(StringWriter stringWriter, string indentString)Creates a new CodeBlocker with the specified StringWriter and custom indent string

Properties

NameTypeDescription
CurrentIndentintGets or sets the current indentation level
IndentStringstringGets the current indent string being used (e.g., "\t", " ", " ")

Methods

NameReturn TypeDescription
WriteLine(string line)voidWrites a line of text with appropriate indentation
WriteLine()voidWrites an empty line with current indentation
Write(string text)voidWrites text without adding a new line
NewLine()voidWrites an empty line without indentation
Indent()voidIncreases the indent level
Outdent()voidDecreases the indent level
ToString()stringReturns the generated code as a string
Create()CodeBlockerStatic factory method to create a new CodeBlocker instance with tab indentation
Create(string indentString)CodeBlockerStatic factory method to create a new CodeBlocker instance with custom indentation
Dispose()voidDisposes of the CodeBlocker and underlying resources

Scope Class

Helper class for managing indentation scopes with automatic brace handling. Built on top of ktsu.ScopedAction for guaranteed resource cleanup and exception safety.

Constructor

NameDescription
Scope(CodeBlocker codeBlocker)Creates a new scope that automatically writes opening brace {, increases indentation, and handles cleanup on disposal

Methods

NameReturn TypeDescription
Dispose()voidDecreases indentation level and writes closing brace } when scope is exited

Behavior

  • On Creation: Writes { and increases indentation level
  • On Disposal: Decreases indentation level and writes }
  • Exception Safety: Guaranteed cleanup even if exceptions occur within the scope
  • Resource Management: Built on ktsu.ScopedAction for reliable resource handling

ScopeWithTrailingSemicolon Class

Variant of Scope that appends a semicolon after the closing brace. Useful for code generation scenarios like C/C++ enum or struct declarations where a trailing semicolon is required.

Constructor

NameDescription
ScopeWithTrailingSemicolon(CodeBlocker codeBlocker)Creates a new scope that automatically writes opening brace {, increases indentation, and handles cleanup on disposal

Methods

NameReturn TypeDescription
Dispose()voidDecreases indentation level and writes closing brace with semicolon }; when scope is exited

Behavior

  • On Creation: Writes { and increases indentation level
  • On Disposal: Decreases indentation level and writes };
  • Exception Safety: Guaranteed cleanup even if exceptions occur within the scope
  • Resource Management: Built on ktsu.ScopedAction for reliable resource handling

Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

About

A specialized utility built on top of IndentedTextWriter that simplifies the process of programmatically generating structured code.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages