Module: Livetext::Helpers

Included in:
Livetext, Livetext::Handler::Import, Livetext::Handler::Mixin, Standard
Defined in:
lib/livetext/helpers.rb

Constant Summary collapse

Space =
" "
Sigil =

Can’t change yet

"."
ESCAPING =
{ "'" => ''', '&' => '&', '"' => '"',
'<' => '&lt;', '>' => '&gt;' }
TTY =
::File.open("/dev/tty", "w")
Comment =
rx(Sigil, Space)
DotCmd =
rx(Sigil)
DollarDot =
/^ *\$\.[A-Za-z]/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.rx(str, space = nil) ⇒ Object



65
66
67
# File 'lib/livetext/helpers.rb', line 65

def self.rx(str, space=nil)
  Regexp.compile("^" + Regexp.escape(str) + "#{space}")
end

Instance Method Details

#check_disallowed(name) ⇒ Object



188
189
190
# File 'lib/livetext/helpers.rb', line 188

def check_disallowed(name)
  friendly_error DisallowedName(name) if disallowed?(name)
end

#debug(*args) ⇒ Object



49
50
51
# File 'lib/livetext/helpers.rb', line 49

def debug(*args)
  puts(*args) if ENV['debug']
end

#escape_html(string) ⇒ Object



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

def escape_html(string)
  enc = string.encoding
  unless enc.ascii_compatible?
    if enc.dummy?
      origenc = enc
      enc = Encoding::Converter.asciicompat_encoding(enc)
      string = enc ? string.encode(enc) : string.b
    end
    table = Hash[ESCAPING.map {|pair|pair.map {|s|s.encode(enc)}}]
    string = string.gsub(/#{"['&\"<>]".encode(enc)}/, table)
    string.encode!(origenc) if origenc
    return string
  end
  string.gsub(/['&\"<>]/, ESCAPING)
end

#file_exists?(file) ⇒ Boolean

Returns:

  • (Boolean)


192
193
194
# File 'lib/livetext/helpers.rb', line 192

def file_exists?(file)
  return File.exist?(file)
end

#find_file(name, ext = ".rb", which = "imports") ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/livetext/helpers.rb', line 53

def find_file(name, ext=".rb", which="imports")
  failed = "#{__method__}: expected 'imports' or 'plugin'"
  raise failed unless %w[imports plugin].include?(which)
  paths = [Livetext::Path.sub(/lib.livetext/, "#{which}/"), "./"]
  base  = "#{name}#{ext}"
  paths.each do |path|
    file = path + base
    return file if File.exist?(file)
  end
  return nil
end

#friendly_error(err) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/livetext/helpers.rb', line 14

def friendly_error(err)
  return graceful_error(err) if self.respond_to?(:graceful_error)
  return self.parent.graceful_error(err) if self.respond_to?(:parent)
  raise err
#  rescue => myerr
#    TTY.puts "--- Warning: friendly_error #{myerr.inspect}"
end

#get_name_data(line) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/livetext/helpers.rb', line 172

def get_name_data(line)
  line = line.chomp
  blank = line.index(" ")
  if blank
    name = line[1..(blank-1)]
    data0 = line[(blank+1)..-1]
  else
    name = line[1..-1]
    data0 = ""
  end
  name = "dot_" + name if %w[include def].include?(name)
  check_disallowed(name)
  api.data = data0  # FIXME kill this?
  [name.to_sym, data0]
end

#grab_file(fname) ⇒ Object



205
206
207
208
209
210
211
# File 'lib/livetext/helpers.rb', line 205

def grab_file(fname)
  File.read(fname)
rescue
  graceful_error NoSuchFile(fname)
  # ::STDERR.puts "Can't find #{fname.inspect} \n "
 # return nil
end

#graceful_error(err, msg = nil) ⇒ Object



277
278
279
280
281
# File 'lib/livetext/helpers.rb', line 277

def graceful_error(err, msg = nil)
  api.dump
  STDERR.puts msg if msg
  raise err
end

#handle_dollar_dot(line) ⇒ Object



116
117
118
119
120
121
122
123
# File 'lib/livetext/helpers.rb', line 116

def handle_dollar_dot(line)
  indent = line.index("$") + 1
  @indentation.push(indent)
  line.sub!(/^ *\$/, "")
  success = handle_dotcmd(line)
  indentation.pop
  success
end

#handle_dotcmd(line, indent = 0) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/livetext/helpers.rb', line 153

def handle_dotcmd(line, indent = 0)
  line = line.sub(/# .*$/, "")
  name, data = get_name_data(line)
  check_disallowed(name)
  case
  when name == :end   # special case
    graceful_error EndWithoutOpening()
  when respond_to?(name)
    success = invoke_dotcmd(name, data)    # was 141
  else
    graceful_error UnknownMethod(name)
  end
  success
end

#handle_scomment(line) ⇒ Object



168
169
170
# File 'lib/livetext/helpers.rb', line 168

def handle_scomment(line)
  return true
end

#include_file(file) ⇒ Object



234
235
236
237
238
# File 'lib/livetext/helpers.rb', line 234

def include_file(file)
  api.data = file
  api.args = [file]
  api.dot_include
end

#invoke_dotcmd(name, data0 = "") ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/livetext/helpers.rb', line 125

def invoke_dotcmd(name, data0="")
  api.data = data0.dup
  args0 = data0.split
  api.args = args0.dup
  method = method(name)
  params = method.parameters
  
  case params.length
  when 0
    retval = send(name)
  when 2
    retval = send(name, args0, data0)
  when 3
    processed_body = api.body(false)
    retval = send(name, args0, data0, processed_body)
  when 4
    if params[3][1] == :raw 
      raw_body = api.body(true)
      retval = send(name, args0, data0, raw_body, true)
    else
      raise "4th parameter is not :raw!"
    end
  else
    raise "#{name} has #{params.length} parameters!"
  end
  retval
end

#onoff(arg) ⇒ Object

helper

Raises:

  • (ExpectedOnOff)


240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/livetext/helpers.rb', line 240

def onoff(arg)   # helper
  arg ||= "on"
  raise ExpectedOnOff unless String === arg
  case arg.downcase
    when "on"
      return true
    when "off"
      return false
  else
    raise ExpectedOnOff
  end
end

#process_file(fname, btrace = false) ⇒ Object

FIXME process_file should call process ?



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/livetext/helpers.rb', line 75

def process_file(fname, btrace=false)
  unless File.exist?(fname)
    api.dump
    raise FileNotFound(fname) 
  end
  setfile(fname)
  text = File.readlines(fname)
  enum = text.each
  @backtrace = btrace
  source(enum, fname, 0)
  line = nil
  loop do
    line = nextline
    break if line.nil?
    success = process_line(line)
    break unless success
  end
  api.close_paragraph  # Close any open paragraph
  val = finalize rescue nil
  @body    # FIXME?   @body.join("\n")  # array
  return true
end

#process_line(line) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/livetext/helpers.rb', line 98

def process_line(line)
  success = true
  case line  # must apply these in order
  when Comment
    success = handle_scomment(line)
  when DotCmd
    success = handle_dotcmd(line)       # was 102
  when DollarDot
    success = handle_dollar_dot(line)
  else
    api.passthru(line)  # must succeed?
  end
  success
rescue => err
  STDERR.puts "ERROR: #{err.inspect}\n#{err.backtrace.join("\n")}"
  exit
end

#read_variables(file) ⇒ Object



196
197
198
199
# File 'lib/livetext/helpers.rb', line 196

def read_variables(file)
  pairs = File.readlines(file).map {|x| x.chomp.split }
  @api.setvars(pairs)
end

#search_upward(file) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/livetext/helpers.rb', line 213

def search_upward(file)
  value = nil
  return file if File.exist?(file)

  count = 1
  loop do
    front = "../" * count
    count += 1
    here = Pathname.new(front).expand_path.dirname.to_s
    break if here == "/"
    path = front + file
    value = path if File.exist?(path)
    break if value
  end
  ::STDERR.puts "Cannot find #{file.inspect} from #{Dir.pwd}" unless value
 return value
rescue
  ::STDERR.puts "Can't find #{file.inspect} from #{Dir.pwd}"
 return nil
end

#set_variables(pairs) ⇒ Object



201
202
203
# File 'lib/livetext/helpers.rb', line 201

def set_variables(pairs)
  @api.setvars(pairs)
end

#setfile(file) ⇒ Object



262
263
264
265
266
267
268
269
270
271
# File 'lib/livetext/helpers.rb', line 262

def setfile(file)
  if file
    api.setvar(:File, file)
    dir = File.dirname(File.expand_path(file))
    api.setvar(:FileDir, dir)
  else
    api.setvar(:File,    "[no file]")
    api.setvar(:FileDir, "[no dir]")
  end
end

#setfile!(file) ⇒ Object

FIXME why does this variant exist?



273
274
275
# File 'lib/livetext/helpers.rb', line 273

def setfile!(file)  # FIXME why does this variant exist?
  api.setvar(:File, file)
end

#setvar(var, val) ⇒ Object



253
254
255
256
257
258
259
260
# File 'lib/livetext/helpers.rb', line 253

def setvar(var, val)
  api.setvar(var, val)
#    str, sym = var.to_s, var.to_sym
#    Livetext::Vars[str] = val
#    Livetext::Vars[sym] = val
#    @_vars[str] = val
#    @_vars[sym] = val
end

#showme(obj, tag = "") ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/livetext/helpers.rb', line 38

def showme(obj, tag = "")
  whence = caller[0]
  file, line, meth = whence.split(":")
  file = File.basename(file)
  meth = meth[4..-2]
  tag << " =" if tag
  hide_class = [true, false, nil].include?(obj)
  klass = hide_class ? "" : "(#{obj.class}) "
  puts " #{tag} #{klass}#{obj.inspect}  in ##{meth}  [#{file} line #{line}]"
end