Module: WLang::IntelligentBuffer::Methods

Included in:
WLang::IntelligentBuffer
Defined in:
lib/wlang/intelligent_buffer.rb

Overview

Some string utilities

Instance Method Summary collapse

Instance Method Details

#<<(str, block = false) ⇒ Object

Pushes a string, aligning it first



74
75
76
77
78
79
80
# File 'lib/wlang/intelligent_buffer.rb', line 74

def <<(str, block=false)
  if block and is_multiline?(str) and stripped = strip_block(str)
    str = tabto(stripped, last_column(self)-1)
    str = str.match(/\A[\t ]*/).post_match
  end
  super(str)
end

#column_of(str, index) ⇒ Object

Returns column number of a specific offset Credits: Treetop and Facets 2.0.2



58
59
60
61
62
63
64
65
66
# File 'lib/wlang/intelligent_buffer.rb', line 58

def column_of(str, index)
  return 1 if index == 0
  newline_index = str.rindex("\n", index - 1)
  if newline_index
    index - newline_index
  else
    index + 1
  end
end

#indent(str, n) ⇒ Object

Positive or negative indentation of str Credits: Treetop and Facets 2.0.2



21
22
23
24
25
26
27
# File 'lib/wlang/intelligent_buffer.rb', line 21

def indent(str, n)
  if n >= 0
    str.gsub(/^/, ' ' * n)
  else
    str.gsub(/^ {0,#{-n}}/, "")
  end
end

#is_multiline?(str) ⇒ Boolean

Checks if str contains multiple lines

Returns:

  • (Boolean)


30
31
32
# File 'lib/wlang/intelligent_buffer.rb', line 30

def is_multiline?(str)
  str =~ /\n/ ? true : false
end

#last_column(str) ⇒ Object

Returns the column of the last character



69
70
71
# File 'lib/wlang/intelligent_buffer.rb', line 69

def last_column(str)
  column_of(str, str.length)
end

#strip_block(str) ⇒ Object

Strips a multiline block.

Example:

([\t ]*\n)?
([\t ]\n)*
[\t ]*some text here\n
[\t ]*  indented also\n?
[\t ]*

becomes:

some text here\n
  indented also\n


48
49
50
51
52
53
54
# File 'lib/wlang/intelligent_buffer.rb', line 48

def strip_block(str)
  match = str.match(/\A[\t ]*\n?/)
  str = match.post_match if match
  match = str.match(/\n[\t ]*\Z/)
  str = (match.pre_match << "\n") if match
  str
end

#tabto(str, n) ⇒ Object

Aligns str at left offset n Credits: Treetop and Facets 2.0.2



11
12
13
14
15
16
17
# File 'lib/wlang/intelligent_buffer.rb', line 11

def tabto(str, n)
  if str =~ /^( *)\S/
    indent(str, n - $1.length)
  else
    str
  end
end

#wlang_append(str, block) ⇒ Object

WLang explicit appending



83
84
85
# File 'lib/wlang/intelligent_buffer.rb', line 83

def wlang_append(str, block)
  self.<<(str, block)
end