# File: olcedit.rb # Author: Craig Smith # This source code copyright (C) 2009 Craig Smith # All rights reserved. # # Released under the terms of the GNU Public License # See COPYING file for additional information. # # OLC multiline editor class OlcEditor attr_accessor :editstr, :done def initialize(str) self.editstr = str self.done = false end def edit_display(str) header =<<EOD ======== Zombie String Editor ======== (Based on Teensy) Type .h on a new line for help Terminate with a @ on a blank line. ====================================== EOD i = 0 header + str.gsub(/^/){"#{i+=1}: "} end # Attempt to fix original word_wrap function # Word wrap needs to end with a \n for some reason :/ def word_wrap(s, len) lines = String.new line = String.new # remove \r\n s.gsub!(/[\r\n]/, " ") s.split(" ").each do |word| if word.size + line.size < len line += word + " " else lines += line + "\n" line = word + " " end end lines += line if line.size > 0 lines += "\n" lines end def parse(args) case args when nil return "What??" when /^\.h/ return <<EOD @edit help (commands on blank line): .r /old/new/ - replace a substring .h - get help (this info) .s - show string so far .ww [width] - word wrap string (width optional) defaults to 76 .c - clear string so far .ld <num> - delete line <num> .li <num> <txt> - insert <txt> before line <num> .lr <num> <txt> - replace line <num> with <txt> @ - end string EOD when /^\.c/ @editstr = "" return "Cleared." when /^\.s/ return(edit_display(@editstr)) when /^\.r\s+\/(.+)?\/(.+)?\// @editstr.gsub!($1, $2) when /^\.ww\s+(\d+)/, /^\.ww/ if $1 @editstr = word_wrap(@editstr, $1) else @editstr = word_wrap(@editstr, 76) end when /^\.ld\s+(\d+)/ idx = $1.to_i return if idx < 1 idx -= 1 lines = @editstr.split("\n") lines.delete_at(idx) @editstr = lines.join("\n") when /^\.li\s+(\d+)\s+(.*)?$/ idx = $1.to_i return if idx < 1 idx -= 1 nl = $2 lines = @editstr.split("\n") lines.insert(idx, nl + "\n") @editstr = lines.join("\n") when /^\.lr\s+(\d+)\s+(.*)?$/ idx = $1.to_i return if idx < 1 idx -= 1 nl = $2 lines = @editstr.split("\n") lines[idx] = nl + "\n" @editstr = lines.compact.join("\n") when /^@/ self.done = true return nil when /^\./ return "Invalid command." else @editstr << args << "\n" end end end