Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/rbibtex/string.rb

Overview

Some string handling routines for wordwrapping and tabifying.

Instance Method Summary collapse

Instance Method Details

#deindent(indent = self.scan(/^\s*/).map{|e|e.length}.min) ⇒ Object

Remove indentation. The optional argument gives the number of spaces to indent by. Will not work correctly if the string contains tab characters.



53
54
55
# File 'lib/rbibtex/string.rb', line 53

def deindent(indent = self.scan(/^\s*/).map{|e|e.length}.min)
  self.gsub(/^ {0,#{indent}}/, "")
end

#deindent_hanging(indent = self.scan(/(?:\n)(\s*)(?=\S)/).flatten.map{|e|e.length}.min) ⇒ Object

Deindent ignoring the first line. Will not work correctly if the string contains tab characters



44
45
46
# File 'lib/rbibtex/string.rb', line 44

def deindent_hanging(indent = self.scan(/(?:\n)(\s*)(?=\S)/).flatten.map{|e|e.length}.min)
  deindent(indent)
end

#indent(indent = 2) ⇒ Object

Indent by indent spaces



34
35
36
# File 'lib/rbibtex/string.rb', line 34

def indent(indent = 2)
  self.gsub(/^/, " " * indent)
end

#indent_hanging(indent = 2) ⇒ Object

Indent everything but the first line



23
24
25
26
27
28
29
30
31
# File 'lib/rbibtex/string.rb', line 23

def indent_hanging(indent = 2)
  first, rest = *self.split("\n", 2)
  return "" unless first
  if rest
    first + "\n" + (rest.indent(indent))
  else
    first
  end
end

#remove_trailing_whitespaceObject



48
49
50
# File 'lib/rbibtex/string.rb', line 48

def remove_trailing_whitespace
  self.gsub(/\s+$/, "")
end

#untabify(tab_width = 8) ⇒ Object

Substitute tabs with spaces



39
40
41
# File 'lib/rbibtex/string.rb', line 39

def untabify(tab_width = 8)
  self.gsub(/\t/, " "*tab_width)
end

#unwrapObject

Change paragraphs (delimited by two blank lines) into one liners. Indented text is left as is.



58
59
60
61
62
# File 'lib/rbibtex/string.rb', line 58

def unwrap
  self.sub(/\A\n+/i, '').split(/\n(?:\s*\n)+/).map { | paragraph |
    paragraph.gsub(/((?:\n|^)\S[^\n]*)\n(?=\S)/, "\\1 ")
  }.join("\n\n")
end

#wrap(width = 78) ⇒ Object

Do a wordwrap. Will not work correctly if the string contains tab characters



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rbibtex/string.rb', line 4

def wrap(width = 78)
  raise "Invalid width" if width < 0
  self.split("\n", -1).map { | line |
    indent = line[/\A\s*/]
    line = line[/\A\s*(.*)\Z/, 1]
    result = [""]
    line.split(/(?=\s+)/).each do | token |
	if result[-1].length + token.length <= width
 result[-1] << token
	else
 result << token[/\A\s*(.*)\Z/, 1]
	end
    end
    result.shift if result.first == ""
    result.map{ |subline| indent + subline }
  }.join("\n")
end