Class: RubynCode::CLI::StreamFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyn_code/cli/stream_formatter.rb

Overview

Formats streamed text on-the-fly with markdown rendering. Buffers code blocks until they close, then syntax-highlights them. Applies inline formatting (bold, code, headers) as text arrives.

Instance Method Summary collapse

Constructor Details

#initialize(_renderer = nil) ⇒ StreamFormatter

Returns a new instance of StreamFormatter.



12
13
14
15
16
17
18
19
# File 'lib/rubyn_code/cli/stream_formatter.rb', line 12

def initialize(_renderer = nil)
  @pastel = Pastel.new
  @rouge_formatter = Rouge::Formatters::Terminal256.new(theme: Rouge::Themes::Monokai.new)
  @buffer = +''
  @in_code_block = false
  @code_lang = nil
  @code_buffer = +''
end

Instance Method Details

#feed(text) ⇒ Object

Feed a chunk of streamed text



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rubyn_code/cli/stream_formatter.rb', line 22

def feed(text)
  @buffer << text

  # Process complete lines from the buffer
  while (newline_idx = @buffer.index("\n"))
    line = @buffer.slice!(0, newline_idx + 1)
    process_line(line)
  end

  # Print any remaining partial line (no newline yet) if not in a code block
  return if @in_code_block || @buffer.empty?

  $stdout.print format_inline(@buffer)
  $stdout.flush
  @buffer = +''
end

#flushObject

Flush any remaining buffered content



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rubyn_code/cli/stream_formatter.rb', line 40

def flush
  unless @buffer.empty?
    if @in_code_block
      @code_buffer << @buffer
      render_code_block
    else
      $stdout.print format_inline(@buffer)
    end
    @buffer = +''
  end

  # Flush unclosed code block
  render_code_block if @in_code_block && !@code_buffer.empty?
  $stdout.flush
end