def check_word(): """ Check the current word and try to push a help message and a completion """ line = lisp.buffer_substring(lisp.line_beginning_position(),lisp.point()) lines= lisp.buffer_substring(1,lisp.point()).splitlines() lines.reverse() d = find_completion(line,lines) if d[0]: f,completions,target = d #lisp.message("Found %d completions\n%s"%(len(completions),curType)) help_str = make_help_message(completions) # make sure we're probably running X: if lisp.window_system() is not None and \ lisp.pos_tip_show is not None: # make sure extension is installed lisp.pos_tip_show(help_str,None,None,None,0) else: lisp.message(help_str) # just use the emacs mini-buffer if len(completions)==1:#if there's only one completion, just insert it d = completions[0].data['name'][len(target):] if len(d):lisp.insert(d) else: lisp.message(d[1])
def emacs_engine(self, flag, find_limits): """\ Rebox text while obeying FLAG. Call FIND_LIMITS to discover the extent of the boxed comment. """ # `C-u -' means that box style is to be decided interactively. if flag == lisp['-']: flag = self.ask_for_style() # If FLAG is zero or negative, only change default box style. if isinstance(flag, int) and flag <= 0: self.default_style = -flag lisp.message("Default style set to %d" % -flag) return # Decide box style and refilling. if flag is None: style = self.default_style refill = True elif isinstance(flag, int): if self.default_style is None: style = flag else: style = merge_styles(self.default_style, flag) refill = True else: flag = flag.copy() if isinstance(flag, list): style = self.default_style refill = False else: lisp.error("Unexpected flag value %s" % flag) # Prepare for reboxing. lisp.message("Reboxing...") checkpoint = lisp.buffer_undo_list.value() start, end = find_limits() text = lisp.buffer_substring(start, end) width = lisp.fill_column.value() tabify = lisp.indent_tabs_mode.value() is not None point = lisp.point() if start <= point < end: position = point - start else: position = None # Rebox the text and replace it in Emacs buffer. old_style, new_style, text, position = engine( text, style=style, width=width, refill=refill, tabify=tabify, position=position) if text is None: lisp.error("Cannot rebox to style %d" % new_style) lisp.delete_region(start, end) lisp.insert(text) if position is not None: lisp.goto_char(start + position) # Collapse all operations into a single one, for Undo. self.clean_undo_after(checkpoint) # We are finished, tell the user. if old_style == new_style: lisp.message("Reboxed with style %d" % old_style) else: lisp.message("Reboxed from style %d to %d" % (old_style, new_style))
def get_buffer_content_prev(bend): where_am_i = lisp.point() lisp.beginning_of_buffer() st = lisp.point() s = lisp.buffer_substring(st, bend) lisp.goto_char(where_am_i) return s
def get_region(self): ''' 获得这个buffer对象中被选中的部分文字 ''' lisp('(set-buffer %s)' % self.varname) b, e = lisp.region_beginning(), lisp.region_end() s = lisp.buffer_substring(b, e) return s
def get_block_content(start_tag, end_tag): remember_where = lisp.point() block_begin = lisp.search_backward(start_tag) block_end = lisp.search_forward(end_tag) block_end = lisp.search_forward(end_tag) content = lisp.buffer_substring(block_begin, block_end) lisp.goto_char(remember_where) return block_begin, block_end, content
def get_block_content(start_tag, end_tag): remember_where = lisp.point() block_begin = lisp.search_backward(start_tag) lisp.goto_char(remember_where) block_end = lisp.search_forward(end_tag) content = lisp.buffer_substring(block_begin, block_end) lisp.goto_char(remember_where) return block_begin, block_end, content
def thing_at_point(): right_set = left_set = set(['\n', ' ']) curridx = lisp.point() curr = '' while (curr in right_set) == False: curr = lisp.buffer_substring(curridx, curridx + 1) curridx += 1 start = curridx - 1 curridx = lisp.point() curr = '' while (curr in left_set) == False: curr = lisp.buffer_substring(curridx - 1, curridx) curridx -= 1 end = curridx + 1 s = lisp.buffer_substring(start, end) return s, end
def get_block_content(start_tag, end_tag): remember_where = lisp.point() block_end = lisp.search_forward(end_tag) block_begin = lisp.search_backward(start_tag) content = lisp.buffer_substring(block_begin, block_end) content = re.sub("\\\\begin{minted}.*?{python}", "", content) content = re.sub("\\\\end{minted}", "", content) lisp.goto_char(remember_where) return block_begin, block_end, content
def thing_at_point(): right_set = left_set = set(['\n',' ']) curridx = lisp.point() curr='' while (curr in right_set) == False: curr = lisp.buffer_substring(curridx, curridx+1) curridx += 1 start = curridx-1 curridx = lisp.point() curr='' while (curr in left_set) == False: curr = lisp.buffer_substring(curridx-1, curridx) curridx -= 1 end = curridx+1 s = lisp.buffer_substring(start, end) return s, end
def get_block_content(start_tag, end_tag): remember_where = lisp.point() block_end = lisp.search_forward(end_tag) block_begin = lisp.search_backward(start_tag) content = lisp.buffer_substring(block_begin, block_end) content = re.sub("\\\\begin{minted}.*?{python}","",content) content = re.sub("\\\\end{minted}","",content) lisp.goto_char(remember_where) return block_begin, block_end, content
def camelCase_to_underscore(): start, end = lisp.point(), lisp.mark(True) text = lisp.buffer_substring(start, end) replacement =re.sub(r'\w+', lambda x: "".join(upper_split_gen(x)), text) lisp.delete_region(start, end) lisp.insert(replacement)
def get_region(delete=0): """Returns the text of the current region, optionally deleting the region from the buffer.""" start = lisp.point() end = lisp.mark(lisp.t) text = lisp.buffer_substring(start, end) if delete: lisp.delete_region(start, end) return text
def run_py_code(): remember_where = lisp.point() # check if the line contains \inputminted lisp.beginning_of_line() l1 = lisp.point() lisp.end_of_line() l2 = lisp.point() line = lisp.buffer_substring(l1,l2) # if code comes from file # get code content from latex block_begin,block_end,content = get_block_content("```python","```\n") # we have code content at this point # scan content to find plt.plot(). if there is, scan buffer # previous to *here* to determine order of _this_ plt.plot(), and # give it an appropiate index that will be appended to the end of # the .png image file, i.e. [buffer name]_[index].png. plt.plot() # commands will be replaced by the corresponding plt.savefig # command. # generate savefig for execution code (no output in emacs yet) bc = lisp.buffer_string() plt_count_before = len(re.findall('plt\.savefig\(',bc)) base = os.path.splitext(lisp.buffer_name())[0] f = '%s_%s.png' % (base, two_digit(plt_count_before+1)) rpl = "plt.savefig('%s')" % f show_replaced = True if "plt.show()" in content else False content=content.replace("plt.show()",rpl) content="plt.figure();\n"+content include_graphics_command = "![](%s)" % f # we have code content at this point start = time.time() with capture_output() as io: res_code = ip.run_cell(content) res = io.stdout elapsed = (time.time() - start) if len(res) > 0: display_results(block_end, res) # display it if show_replaced: lisp.goto_char(block_end) lisp.forward_line(2) # skip over end verbatim, leave one line emtpy lisp.insert('\n' + include_graphics_command + '\n') lisp.scroll_up(1) # skip over end verbatim, leave one line emtpy lisp.goto_char(remember_where) lisp.replace_string("plt.show()",rpl,None,block_begin,block_end) lisp.goto_char(remember_where) lisp.message("Ran in " + str(elapsed) + " seconds")
def run_py_code(): remember_where = lisp.point() # check if the line contains \inputminted lisp.beginning_of_line() l1 = lisp.point() lisp.end_of_line() l2 = lisp.point() line = lisp.buffer_substring(l1, l2) # if code comes from file # get code content from latex block_begin, block_end, content = get_block_content("```python", "```\n") # we have code content at this point # scan content to find plt.plot(). if there is, scan buffer # previous to *here* to determine order of _this_ plt.plot(), and # give it an appropiate index that will be appended to the end of # the .png image file, i.e. [buffer name]_[index].png. plt.plot() # commands will be replaced by the corresponding plt.savefig # command. # generate savefig for execution code (no output in emacs yet) bc = lisp.buffer_string() plt_count_before = len(re.findall('plt\.savefig\(', bc)) base = os.path.splitext(lisp.buffer_name())[0] f = '%s_%s.png' % (base, two_digit(plt_count_before + 1)) rpl = "plt.savefig('%s')" % f show_replaced = True if "plt.show()" in content else False content = content.replace("plt.show()", rpl) content = "plt.figure();\n" + content include_graphics_command = "![](%s)" % f # we have code content at this point start = time.time() with capture_output() as io: res_code = get_ip().run_cell(content) res = io.stdout elapsed = (time.time() - start) if len(res) > 0: display_results(block_end, res) # display it if show_replaced: lisp.goto_char(block_end) lisp.forward_line(2) # skip over end verbatim, leave one line emtpy lisp.insert('\n' + include_graphics_command + '\n') lisp.scroll_up(1) # skip over end verbatim, leave one line emtpy lisp.goto_char(remember_where) lisp.replace_string("plt.show()", rpl, None, block_begin, block_end) lisp.goto_char(remember_where) lisp.message("Ran in " + str(elapsed) + " seconds")
def run_text(): start = lisp.point() end = lisp.mark(True) if start > end: start, end = end, start text = lisp.buffer_substring(start, end) if len(text): client.run_text(text) else: # TODO Complain in message bar pass
def replace_region(replacer): start = lisp.point() end = lisp.mark(True) if start > end: start, end = end, start text = lisp.buffer_substring(start, end) replacement = replacer(text) lisp.delete_region(start, end) lisp.insert(replacement)
def verb_exists(): remem = lisp.point() lisp.forward_line(2) lisp.beginning_of_line() verb_line_b = lisp.point() lisp.end_of_line() verb_line_e = lisp.point() verb_line = lisp.buffer_substring(verb_line_b, verb_line_e) lisp.goto_char(remem) if "\\begin{verbatim}" in verb_line: return True else: return False
def verb_exists(): remem = lisp.point() lisp.forward_line(1) lisp.beginning_of_line() verb_line_b = lisp.point() lisp.end_of_line() verb_line_e = lisp.point() verb_line = lisp.buffer_substring(verb_line_b, verb_line_e) lisp.goto_char(remem) if "```text" in verb_line: return True else: return False
def pexec_region(): global glob start = time.time() start, end = lisp.point(), lisp.mark(lisp.t) content = lisp.buffer_substring(start, end) lines = content.split("\n") for line in lines: line = line.replace("\n","") if line != "": c = compile(source=line,filename="",mode="single") eval(c,glob) elapsed = (time.time() - start) lisp.message("Ran in " + str(elapsed) + " seconds")
def thing_at_point_regex(right, left): """ Mine is a lot better than the emacs thingy which does not 'get' types with generics """ curridx = lisp.point() curr='' while (re.search(right, curr) ) == None: curr = lisp.buffer_substring(curridx, curridx+1) curridx += 1 start = curridx-1 curridx = lisp.point() curr='' while (re.search(left, curr) ) == None: curr = lisp.buffer_substring(curridx-1, curridx) curridx -= 1 end = curridx+1 s = lisp.buffer_substring(start, end) return s, end
def thing_at_point(right_set, left_set): """ Mine is a lot better than the emacs thingy which does not 'get' types with generics """ curridx = lisp.point() curr='' while (curr in right_set) == False: curr = lisp.buffer_substring(curridx, curridx+1) curridx += 1 start = curridx-1 curridx = lisp.point() curr='' while (curr in left_set) == False: curr = lisp.buffer_substring(curridx-1, curridx) curridx -= 1 end = curridx+1 s = lisp.buffer_substring(start, end) return s, end
def put_import (fname, imp): print "in put_import" print fname print imp content = lisp.buffer_substring(1, lisp.point()) print content for m in re.finditer("(import\s.*?);", content): print "mgroup="+m.group(1) print imp if (re.search(imp, m.group(1))): lisp.message("Already imported") return insert_where = re.search("import\s.*;", content).span()[1] lisp.goto_char(insert_where + 1) lisp.insert("\nimport " + imp + ";")
def cut_region(mode='string'): """Return the active region and remove it from Emacs. The mode parameter (default 'string') defines whether to return the region as a string or as a list of lines (mode='list'). It is the caller's responsibility to insert the updated text at the end back in the Emacs buffer with a call to lisp.insert(...).""" start, end = lisp.point(), lisp.mark(lisp.t) # BUG: buffer_substring() can't extract regions with dos line endings (\r\n) # It dumps a traceback. region = lisp.buffer_substring(start, end) if mode == 'list': region = region.splitlines() lisp.delete_region(start, end) return region
def wrapper(): if lisp.mark_active.value(): # fetch marked text start = lisp.point() end = lisp.mark(True) else: # fetch full line start = lisp.line_beginning_position() end = lisp.line_end_position() start, end = min(start, end), max(start, end) text = lisp.buffer_substring(start, end) new_text = func(text) if isinstance(new_text, str): # replace text with new text lisp.delete_region(start, end) lisp.insert(new_text)
def display_results(end_block, res): lisp.goto_char(end_block) lisp.forward_line(2) lisp.beginning_of_line() verb_line_b = lisp.point() lisp.end_of_line() verb_line_e = lisp.point() verb_line = lisp.buffer_substring(verb_line_b, verb_line_e) if "\\begin{verbatim}" in verb_line: verb_begin,verb_end,content = get_block_content("\\begin{verbatim}","\\end{verbatim}") lisp.delete_region(verb_begin, verb_end) lisp.goto_char(verb_begin) else: lisp.backward_line_nomark(1) lisp.insert("\n") res=res.replace("\r","") lisp.insert("\\begin{verbatim}\n") lisp.insert(res) lisp.insert("\\end{verbatim}")
def new(language, region_start=None, region_end=None): """ Create a new paste. Use the given (programming) ``language`` for server side highlighting. If ``region_start`` and ``region_end`` are given, create a paste with the contents of this region. When called interactively with transient mark mode enabled and an active mark, create a paste with the contents of the region. Otherwise create a paste with the contents of the whole buffer. """ lodgeit = lodgeIt() mark_active = lisp.mark_active.value() transient_mark_mode = lisp.transient_mark_mode.value() if lisp.interactive and transient_mark_mode and mark_active: # use a region, if we have one region_start = lisp.region_beginning() region_end = lisp.region_end() elif region_start: # otherwise use the given arguments region_start = min(region_start, region_end) region_end = max(region_start, region_end) else: # as last resort, paste the whole buffer region_start = lisp.point_min_marker() region_end = lisp.point_max_marker() code = unicode(lisp.buffer_substring(region_start, region_end)) filename = lisp.buffer_file_name() lisp.message('Transferring paste to server...') paste_id = lodgeit.new_paste(code, language, filename=filename) paste = lodgeit.get_paste_by_id(paste_id) lisp.message( 'New paste with ID {0.id} created. Refer to {0.url}'.format(paste)) if lisp.paste_kill_url.value(): lisp.kill_new(paste.url) if lisp.paste_show_in_browser.value(): lisp.browse_url(paste.url)
def pick_import(): ''' pick the whole line from the list of imports ''' print "in pick import" thing, start = thing_at_point_regex("\n", "\n") prev_buffer = os.environ['BUFFER'] print "-"+prev_buffer+"-" lisp.kill_buffer(lisp.get_buffer("*PyJde*")) lisp.switch_to_buffer(prev_buffer) remember_where = lisp.point() content = lisp.buffer_substring(1, lisp.point()) insert_where = re.search("package\s.*;", content).span()[1] lisp.goto_char(insert_where + 1) lisp.insert("\n\nimport " + thing + ";") lisp.message(thing + " is imported") lisp.goto_char(remember_where) lisp.delete_other_windows()
if 'arg' in globals(): from Pymacs import lisp import jarvis.emacs.utils as utils # Sample code : break on whitespace start, end = lisp.point(), lisp.mark(True) text = lisp.buffer_substring(start, end) rewriteRules = { ';': '', '::': '.', '( ': '(', ' )': ')', '->': '.', 'new ': '', '//': '#' } for k, v in rewriteRules.iteritems(): text = text.replace(k, v) lisp.delete_region(start, end) lisp.insert(text)
def get_line_string (): start = lisp.line_beginning_position() end = lisp.line_end_position() return start, end, lisp.buffer_substring(start, end)
def break_on_whitespace(): start, end = lisp.point(), lisp.mark(True) words = lisp.buffer_substring(start, end).split() lisp.delete_region(start, end) lisp.insert('\n'.join(words))
def run_py_code(): remember_where = lisp.point() # check if the line contains \inputminted lisp.beginning_of_line() l1 = lisp.point() lisp.end_of_line() l2 = lisp.point() line = lisp.buffer_substring(l1,l2) # if code comes from file if "\\inputminted" in line: block_begin = lisp.point() lisp.message(line) py_file = re.search("\{python\}\{(.*?)\}", line).groups(1)[0] # get code content from file curr_dir = os.path.dirname(lisp.buffer_file_name()) content = open(curr_dir + "/" + py_file).read() block_end = l2 # end of block happens to be end of include file line lisp.goto_char(remember_where) else: # get code content from latex block_begin,block_end,content = get_block_content("\\begin{minted}","\\end{minted}") # we have code content at this point # scan content to find plt.plot(). if there is, scan buffer # previous to *here* to determine order of _this_ plt.plot(), and # give it an appropiate index that will be appended to the end of # the .png image file, i.e. [buffer name]_[index].png. plt.plot() # commands will be replaced by the corresponding plt.savefig # command. # generate savefig for execution code (no output in emacs yet) bc = get_buffer_content_prev(block_begin) plt_count_before = len(re.findall('plt\.savefig\(',bc)) base = os.path.splitext(lisp.buffer_name())[0] f = '%s_%s.png' % (base, two_digit(plt_count_before+1)) rpl = "plt.hold(False)\nplt.savefig('%s')\nplt.hold(False)" % f show_replaced = True if "plt.show()" in content else False content=content.replace("plt.show()",rpl) include_graphics_command = "\\includegraphics[height=6cm]{%s}" % f #(ip) = get_kernel_pointer(lisp.buffer_name()) start = time.time() with capture_output() as io: res_code = ip.run_cell(content) res = io.stdout elapsed = (time.time() - start) display_results(block_end, res) # display it # generate includegraphics command if show_replaced: lisp.forward_line(2) # skip over end verbatim, leave one line emtpy lisp.insert(include_graphics_command + '\n') lisp.scroll_up(1) # skip over end verbatim, leave one line emtpy lisp.goto_char(remember_where) lisp.replace_string("plt.show()",rpl,None,block_begin,block_end) lisp.goto_char(remember_where) if "plt.savefig" in content: lisp.preview_buffer() lisp.message("Ran in " + str(elapsed) + " seconds")
def get_buffer_content_prev(bend): where_am_i = lisp.point() lisp.beginning_of_buffer(); st = lisp.point() s = lisp.buffer_substring(st,bend) lisp.goto_char(where_am_i) return s
def new_from_region(start, end, language): """Pastes the current selection""" code = unicode(lisp.buffer_substring(start, end)) filename = lisp.buffer_file_name() new_paste(code, language, filename=filename)
if 'arg' in globals(): from Pymacs import lisp # Retrieve current buffer file name filename = lisp.buffer_file_name() # Sample code : break on whitespace start, end = lisp.point(), lisp.mark(True) words = lisp.buffer_substring(start, end).split("\n") words = map(lambda x : x.rstrip(" "), words) lisp.delete_region(start, end) lisp.insert('\n'.join(words))
if 'arg' in globals(): from Pymacs import lisp # Retrieve current buffer file name filename = lisp.buffer_file_name() # Sample code : break on whitespace start, end = lisp.point(), lisp.mark(True) words = lisp.buffer_substring(start, end).split("\n") words = map(lambda x: x.rstrip(" "), words) lisp.delete_region(start, end) lisp.insert('\n'.join(words))
def run_py_code(): remember_where = lisp.point() # check if the line contains \inputminted lisp.beginning_of_line() l1 = lisp.point() lisp.end_of_line() l2 = lisp.point() line = lisp.buffer_substring(l1, l2) # if code comes from file if "\\inputminted" in line: block_begin = lisp.point() lisp.message(line) py_file = re.search("\{python\}\{(.*?)\}", line).groups(1)[0] # get code content from file curr_dir = os.path.dirname(lisp.buffer_file_name()) content = open(curr_dir + "/" + py_file).read() block_end = l2 # end of block happens to be end of include file line lisp.goto_char(remember_where) else: # get code content from latex block_begin, block_end, content = get_block_content( "\\begin{minted}", "\\end{minted}") # we have code content at this point # scan content to find plt.plot(). if there is, scan buffer # previous to *here* to determine order of _this_ plt.plot(), and # give it an appropiate index that will be appended to the end of # the .png image file, i.e. [buffer name]_[index].png. plt.plot() # commands will be replaced by the corresponding plt.savefig # command. # generate savefig for execution code (no output in emacs yet) bc = lisp.buffer_string() plt_count_before = len(re.findall('plt\.savefig\(', bc)) base = os.path.splitext(lisp.buffer_name())[0] f = '%s_%s.png' % (base, two_digit(plt_count_before + 1)) rpl = "plt.savefig('%s')" % f show_replaced = True if "plt.show()" in content else False content = content.replace("plt.show()", rpl) content = "plt.figure()\n" + content include_graphics_command = "\\includegraphics[height=6cm]{%s}" % f #(ip) = get_kernel_pointer(lisp.buffer_name()) start = time.time() with capture_output() as io: res_code = get_ip().run_cell(content) res = io.stdout elapsed = (time.time() - start) display_results(block_end, res) # display it # generate includegraphics command if show_replaced: lisp.forward_line(2) # skip over end verbatim, leave one line emtpy lisp.insert(include_graphics_command + '\n') lisp.scroll_up(1) # skip over end verbatim, leave one line emtpy lisp.goto_char(remember_where) lisp.replace_string("plt.show()", rpl, None, block_begin, block_end) lisp.goto_char(remember_where) if "plt.savefig" in content: lisp.preview_buffer() lisp.message("Ran in " + str(elapsed) + " seconds")
def run_py_code(): remember_where = lisp.point() # check if the line contains \inputminted lisp.beginning_of_line() l1 = lisp.point() lisp.end_of_line() l2 = lisp.point() line = lisp.buffer_substring(l1,l2) block_begin,block_end,content = get_block_content("```python","```") #lisp.message(content) # we have code content at this point # scan content to find plt.plot(). if there is, scan buffer # previous to *here* to determine order of _this_ plt.plot(), and # give it an appropiate index that will be appended to the end of # the .png image file, i.e. [buffer name]_[index].png. plt.plot() # commands will be replaced by the corresponding plt.savefig # command. # generate savefig for execution code (no output in emacs yet) bc = get_buffer_content_prev(block_begin) plt_count_before = len(re.findall('plt\.savefig\(',bc)) base = os.path.splitext(lisp.buffer_name())[0] f = '%s_%s.png' % (base, two_digit(plt_count_before+1)) rpl = "plt.savefig('%s')" % f show_replaced = True if "plt.show()" in content else False content=content.replace("plt.show()",rpl) include_graphics_command = "![](%s)" % f (kc,kernel,ip) = get_kernel_pointer(lisp.buffer_name()) start = time.time() res = '' with capture_output() as io: ip.run_cell(content) res = io.stdout if kernel.shell.last_known_outflag: etype, value, tb = kernel.shell._get_exc_info() res = str(etype) + " " + str(value) + "\n" elapsed = (time.time() - start) # replace this unnecessary message so output becomes blank if res and len(res) > 0: # if result not empty res = res.replace("Populating the interactive namespace from numpy and matplotlib\n","") display_results(block_end, res) # display it else: display_results(block_end, "") lisp.goto_char(block_end) # generate includegraphics command if show_replaced: lisp.forward_line(2) # skip over end verbatim, leave one line emtpy lisp.insert(include_graphics_command + '\n') #lisp.backward_line_nomark(1) # skip over end verbatim, leave one line emtpy lisp.scroll_up(1) # skip over end verbatim, leave one line emtpy lisp.goto_char(remember_where) lisp.replace_string("plt.show()",rpl,None,block_begin,block_end) lisp.goto_char(remember_where) if "plt.savefig" in content: lisp.preview_buffer() lisp.message("Ran in " + str(elapsed) + " seconds")
def run_py_code(): remember_where = lisp.point() # check if the line contains \inputminted lisp.beginning_of_line() l1 = lisp.point() lisp.end_of_line() l2 = lisp.point() line = lisp.buffer_substring(l1, l2) # if code comes from file if "\\inputminted" in line: lisp.message(line) py_file = re.search("\{python\}\{(.*?)\}", line).groups(1)[0] # get code content from file curr_dir = os.path.dirname(lisp.buffer_file_name()) content = open(curr_dir + "/" + py_file).read() block_end = l2 # end of block happens to be end of include file line lisp.goto_char(remember_where) else: # get code content from latex block_begin, block_end, content = get_block_content( "\\begin{minted}", "\\end{minted}") #lisp.message(content) # we have code content at this point # scan content to find plt.plot(). if there is, scan buffer # previous to *here* to determine order of _this_ plt.plot(), and # give it an appropiate index that will be appended to the end of # the .png image file, i.e. [buffer name]_[index].png. plt.plot() # commands will be replaced by the corresponding plt.savefig # command. # generate savefig for execution code (no output in emacs yet) bc = get_buffer_content_prev(block_begin) plt_count_before = len(re.findall('plt\.savefig\(', bc)) base = os.path.splitext(lisp.buffer_name())[0] f = '%s_%s.png' % (base, two_digit(plt_count_before + 1)) rpl = "plt.savefig('%s')" % f show_replaced = True if "plt.show()" in content else False content = content.replace("plt.show()", rpl) include_graphics_command = "\\includegraphics[height=6cm]{%s}" % f (kc, kernel, ip) = get_kernel_pointer(lisp.buffer_name()) start = time.time() res = '' with capture_output() as io: ip.run_cell(content) res = io.stdout if kernel.shell.last_known_outflag: etype, value, tb = kernel.shell._get_exc_info() res = str(etype) + " " + str(value) + "\n" elapsed = (time.time() - start) # replace this unnecessary message so output becomes blank if res and len(res) > 0: # if result not empty res = res.replace( "Populating the interactive namespace from numpy and matplotlib\n", "") display_results(block_end, res) # display it else: display_results(block_end, "") lisp.goto_char(block_end) # generate includegraphics command if show_replaced: lisp.forward_line(2) # skip over end verbatim, leave one line emtpy lisp.insert(include_graphics_command + '\n') lisp.backward_line_nomark( 1) # skip over end verbatim, leave one line emtpy lisp.goto_char(remember_where) lisp.replace_string("plt.show()", rpl, None, block_begin, block_end) lisp.goto_char(remember_where) if "plt.savefig" in content: lisp.preview_buffer() lisp.message("Ran in " + str(elapsed) + " seconds")