Method: CodeTree.run

Defined in:
lib/xiki/code_tree.rb

.run(code, options = {}) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/xiki/code_tree.rb', line 96

def self.run code, options={}
  b = View.buffer

  orig = Location.new
  orig_left = $el.point

  returned, stdout, e = Code.eval(code)  # Eval code
  # If no stdout (and something was returned), print return value
  if ! stdout.nonempty? and ! returned.nil?
    stdout = self.returned_to_s returned
  else
    $el.message(returned.to_s) if returned and (!returned.is_a?(String) or returned.size < 500)
  end

  stdout = self.draw_exception(e, code) if e

  buffer_changed = b != View.buffer   # Remember whether we left the buffer
  # Insert output if there was any
  if stdout.nonempty?
    # Pull out flags
    if stdout =~ /^:code_tree_option_tree_search\n/
      options[:tree_search] = true
      stdout.sub! /.+\n/, ''   # Remove option
    elsif stdout =~ /^:quote_search_option\n/
      options[:quote_search] = true
      stdout.sub! /.+\n/, ''   # Remove option
    elsif stdout =~ /^:code_tree_option_no_search\n/
      options[:no_search] = true
      stdout.sub! /.+\n/, ''   # Remove option
    end
    ended_up = Location.new

    # Go back to where we were before running code
    orig.go
    indent = Line.indent
    Line.to_left
    Line.next
    left = $el.point

    # Move what they printed over to left margin initally, in case they haven't
    stdout = TextUtil.unindent(stdout)
    stdout.sub!(/\n\n\z/, "\n")   # Remove any double linebreaks at end

    stdout.gsub!(/^/, "#{indent}  ")

    View << stdout  # Insert output
    right = $el.point

    orig.go   # Move cursor back
    ended_up.go   # End up where script took us

    # These are deprecated - eventually pull them out
    if options[:tree_search]   # If they want to do a tree search
      $el.goto_char left
      FileTree.select_next_file
      Tree.search(:left=>left, :right=>right, :recursive=>true)
      return
    end
    if options[:quote_search]   # If they want to do a tree search
      $el.goto_char left
      Search.forward "|"
      Line.to_beginning
      Tree.search(:left=>left, :right=>right, :recursive_quotes=>true)
      return
    end

    # If script didn't move us (line or buffer), do incremental search
    if !options[:no_search] && !buffer_changed && $el.point == orig_left
      # TODO No search if there aren't more than 3 lines
      $el.goto_char left

      Line.to_words

      # Determine how to search based on output!

      Tree.search_appropriately left, right, stdout

    elsif options[:no_search]
      Line.to_beginning :down=>1
    end

  end
end