def main(): d = emacs.get_user_dir("commands") name = arg[0] name = name.replace("-", "_") # Check if command already exists command_file_name = emacs.get_command_file(name, create = True) if command_file_name != None: lisp.message("Command already exists, opening %s" % command_file_name) lisp.find_file(command_file_name) return filename = os.path.join(d, name + ".py") f = open(filename, "w") newcommand = """if 'arg' in globals(): from Pymacs import lisp import jarvis.emacs.utils as utils # 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() lisp.delete_region(start, end) lisp.insert('\\n'.join(words))""" f.write(newcommand) f.close() lisp.pymacs_load("jarvis.emacs", "j-") lisp.find_file(filename)
def pycomplete(s, imports=None): completions = get_all_completions(s, imports) dots = s.split(".") result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == "": if completions: width = lisp.window_width() - 2 colum = width / 20 white = " " msg = "" counter = 0 for completion in completions : if completion.__len__() < 20 : msg += completion + white[completion.__len__():] counter += 1 else : msg += completion + white[completion.__len__() - 20:] counter += 2 if counter >= colum : counter = 0 msg += '\n' else: msg = "no completions!" lisp.message(msg) return result
def doctest_region(): """Run doctests in the current region. Note that this will essentially look at the current region as a 'doctest file', not as python code; if you want to run doctests in python code, use exec_and_doctest_region(). Any errors in the doctests are placed in an emacs buffer called 'Doctest output'. """ text = get_region() parser = doctest.DocTestParser() test = parser.get_doctest(text, _py_globals, "<emacs text selection>", "<emacs text selection>", 0) buf = io.StringIO() runner = doctest.DocTestRunner(verbose=1) runner.run(test, out=buf.write) if runner.failures: out = buf.getvalue() insert_in_other_buffer("Doctest output", out) else: lisp.message("All %d doctest(s) passed." % (runner.tries))
def entry_gen(key): """ generate org record for one bib entry, then insert to file on editing. """ entry = next((x for x in bibs if x['id'] == key), None) if entry is not None: lisp.insert(Template('/$key($resource)/').substitute(key = key, resource = entry2org(entry))) else: lisp.message('No such key in bibtex database')
def command(): c = lisp.completing_read("Enter command:",["update","reload","complete"]) lisp.message(str(c)) if c=="update" or c=="reload": update_state() elif c=="complete": complete_type()
def find_public_methods(): """ retrieves all public methods of class """ try: fname=lisp.buffer_file_name() print "remember:" + lisp.buffer_name() os.environ['BUFFER'] = lisp.buffer_name() project = Project(fname) thing, start = thing_at_point(RIGHT3, LEFT3) thing = thing.replace(".","") print "thing:"+thing pos = lisp.point() type, foundpos = project.find_declaration_type(thing, fname, pos) typefile = project.find_file_for_thing(type, fname) c = Class(project, typefile) public_methods = c.list_all_public() if (len(public_methods) == 0): lisp.message("No public methods found") else: ready_output() lisp.insert("\n") for item in public_methods: lisp.insert(item) lisp.insert("\n") except Exception, e: lisp.message(e)
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 find_imports(): print "test hello" fname=lisp.buffer_file_name() print "remember:" + lisp.buffer_name() os.environ['BUFFER'] = lisp.buffer_name() remember_where = lisp.point() try: fname=lisp.buffer_file_name() project = Project(fname) thing, start = thing_at_point_regex("\W", "\W") print "thing:"+thing imports = project.find_file_for_import(thing) if (len(imports) > 1): ready_output() lisp.insert("\n") for item in imports: lisp.insert(item) lisp.insert("\n") elif (len(imports) == 1): put_import(fname, imports[0]) elif (len(imports) == 0): lisp.message("No import found for " + imports[0]) lisp.goto_char(remember_where) except Exception, e: lisp.message(e)
def doctest_region(): """Run doctests in the current region. Note that this will essentially look at the current region as a 'doctest file', not as python code; if you want to run doctests in python code, use exec_and_doctest_region(). Any errors in the doctests are placed in an emacs buffer called 'Doctest output'. """ text = get_region() parser = doctest.DocTestParser() test = parser.get_doctest( text, _py_globals, "<emacs text selection>", "<emacs text selection>", 0 ) buf = StringIO.StringIO() runner = doctest.DocTestRunner(verbose=1) runner.run(test, out=buf.write) if runner.failures: out = buf.getvalue() insert_in_other_buffer("Doctest output", out) else: lisp.message("All %d doctest(s) passed." % (runner.tries))
def pycomplete(s, imports=None): completions = get_all_completions(s, imports) dots = s.split(".") result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == "": if completions: width = lisp.window_width() - 2 colum = width / 20 white = " " msg = "" counter = 0 for completion in completions: if completion.__len__() < 20: msg += completion + white[completion.__len__():] counter += 1 else: msg += completion + white[completion.__len__() - 20:] counter += 2 if counter >= colum: counter = 0 msg += '\n' else: msg = "no completions!" lisp.message(msg) return result
def languages(): """Returns a list of supported languages.""" lodgeit = lodgeIt() if not lodgeit.has_languages: lisp.message('Fetching list of supported languages from server') return lodgeit.languages.keys()
def occurrences_next(arg, reset): lisp.switch_to_buffer_other_window('*rope-occurrences*', True) if reset: lisp.goto_char(lisp.point_min()) lisp.forward_line(arg) if lisp.eobp(): lisp.message("Cycling rope occurences") lisp.goto_char(lisp.point_min()) occurrences_goto()
def exec_and_doctest_region(): """This function executes the current region as a Python statement or series of statements. Stdout and stderr are redirected to an emacs buffer called 'Python output'. If any of the objects produced by the selected code (functions, classes, etc) have doctests, they are executed automatically, and any errors in them are placed in an emacs buffer called 'Doctest output'.""" code_str = get_region() temp_stdout = StringIO.StringIO() tempLocals = {} old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = temp_stdout sys.stderr = temp_stdout try: exec code_str in _py_globals, tempLocals finally: sys.stdout = old_stdout sys.stderr = old_stderr doctests = [] finder = doctest.DocTestFinder() for obj in tempLocals.values(): if hasattr( obj, "__name__" ): doctests.extend( finder.find(obj) ) buf = StringIO.StringIO() runner = doctest.DocTestRunner(verbose=1) for test in doctests: runner.run(test, out=buf.write) if runner.failures: out = buf.getvalue() insert_in_other_buffer("Doctest output", out) else: if runner.tries: test_info_str = "All %d doctest(s) passed." % (runner.tries) else: test_info_str = "" _py_globals.update( tempLocals ) out = temp_stdout.getvalue() if out: insert_in_other_buffer("Python output", out) messageStr = "Python code executed " \ "successfully. %s" % test_info_str lisp.message( messageStr )
def exec_and_doctest_region(): """This function executes the current region as a Python statement or series of statements. Stdout and stderr are redirected to an emacs buffer called 'Python output'. If any of the objects produced by the selected code (functions, classes, etc) have doctests, they are executed automatically, and any errors in them are placed in an emacs buffer called 'Doctest output'.""" code_str = get_region() temp_stdout = io.StringIO() tempLocals = {} old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = temp_stdout sys.stderr = temp_stdout try: exec(code_str, _py_globals, tempLocals) finally: sys.stdout = old_stdout sys.stderr = old_stderr doctests = [] finder = doctest.DocTestFinder() for obj in list(tempLocals.values()): if hasattr(obj, "__name__"): doctests.extend(finder.find(obj)) buf = io.StringIO() runner = doctest.DocTestRunner(verbose=1) for test in doctests: runner.run(test, out=buf.write) if runner.failures: out = buf.getvalue() insert_in_other_buffer("Doctest output", out) else: if runner.tries: test_info_str = "All %d doctest(s) passed." % (runner.tries) else: test_info_str = "" _py_globals.update(tempLocals) out = temp_stdout.getvalue() if out: insert_in_other_buffer("Python output", out) messageStr = "Python code executed " \ "successfully. %s" % test_info_str lisp.message(messageStr)
def find_file_at_symbol(): """ finds file at point """ fname=lisp.buffer_file_name() a = Project(fname) thing, start = thing_at_point(RIGHT1, LEFT1) file = a.find_file_for_thing(thing, fname) lisp.message(file) lisp.find_file(file)
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 complete_py(): thing, start = thing_at_point() lisp.message(thing) text, matches = ip.complete(thing) lisp.switch_to_buffer("*pytexipy*") lisp.kill_buffer(lisp.get_buffer("*pytexipy*")) lisp.switch_to_buffer_other_window("*pytexipy*") lisp.insert(thing) for item in matches: lisp.insert(item) lisp.insert("\n")
def new_paste(code, language, filename): """Creates a new paste.""" lisp.message('Transferring paste to server...') id = lodgeit.new_paste(code, language, filename=filename) paste = lodgeit.get_paste_by_id(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 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 byte_compile_el_files(): dirs = [".emacs.d/", ".emacs.d/site-lisp/", ".emacs.d/setup/", ".emacs.d/defuns/", "/home/bro/programmer/emacs/predictive/predictive/"] home = os.environ['HOME'] for d in dirs: files = glob.glob(os.path.join(home, d) + "*.el") for f in files: lisp.message("Byte compiling '%s'" % f) lisp._eval('(byte-compile-file "%s")' % f)
def entries_update(): """ search for all org notes and substitute paper resource link with bib entries """ for org in orgs: lisp.message('Update ' + org + ' ...') for index, entry in enumerate(bibs): key = entry['id'] entry_content = entry2org(entry).replace('/', '\/') subs_cmd = Template('sed -i \'\' \"s/$key[(].*[)]/$key($resource)/g\" $org').substitute(key = key, resource = entry_content, org = org) subprocess.check_call(subs_cmd, shell = True) lisp.message('Updated done.')
def goto_definition(): """ go to definition/declaration of the pointer we are looking at """ fname=lisp.buffer_file_name() a = Project(fname) thing, start = thing_at_point(RIGHT1, LEFT1) lisp.message(thing) pos = lisp.point() type, pos = a.find_declaration_type(thing, fname, pos) lisp.goto_char(pos)
def new_paste(code, language, filename): """Creates a new paste.""" lisp.message('Transferring paste to server...') id = lodgeit.new_paste(code, language, filename=filename) paste = lodgeit.get_paste_by_id(id) lisp.message('New paste with id %s created. Refer to %s', paste.id, paste.url) if lisp.paste_kill_url.value(): lisp.kill_new(paste.url) if lisp.paste_show_in_browser.value(): lisp.browse_url(paste.url)
def complete_type(): """ UI attempt to grab completions for a class """ c = lisp.completing_read("Type to complete:",cpp.CppObject.classes) lisp.message("Looking for:"+str(c)) try: t = cpp.CppObject.getByName(c) completions = t.getChildrenByWeakName("") lisp.pos_tip_show(make_help_message(completions),None,None,None,0) except: lisp.message("Couldn't find class "+c)
def byte_compile_el_files(): dirs = [ ".emacs.d/", ".emacs.d/site-lisp/", ".emacs.d/setup/", ".emacs.d/defuns/", "/home/bro/programmer/emacs/predictive/predictive/" ] home = os.environ['HOME'] for d in dirs: files = glob.glob(os.path.join(home, d) + "*.el") for f in files: lisp.message("Byte compiling '%s'" % f) lisp._eval('(byte-compile-file "%s")' % f)
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 get_kernel_pointer(buffer): lisp.message("getting kernel for " + buffer) if buffer not in kernels: lisp.message("creating new " + buffer) km = InProcessKernelManager() km.start_kernel() kc = BlockingInProcessKernelClient(kernel=km.kernel) kc.start_channels() kernel = InProcessKernel() kernels[buffer] = (kc, kernel, kernel.shell.get_ipython()) # run this so that plt, np pointers are ready kc.shell_channel.execute('%pylab inline') return kernels[buffer]
def get_kernel_pointer(buffer): lisp.message("getting kernel for " + buffer) if buffer not in kernels: lisp.message("creating new " + buffer) km = InProcessKernelManager() km.start_kernel() kc = BlockingInProcessKernelClient(kernel=km.kernel) kc.start_channels() kernel = InProcessKernel() kernels[buffer] = (kc,kernel,kernel.shell.get_ipython()) # run this so that plt, np pointers are ready kc.shell_channel.execute('%pylab inline') return kernels[buffer]
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 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 update_state(): """ Updates the current state by looking for included files and parsing them """ lisp.message("Loading... this might take a while.") this_text = lisp.buffer_string() cwd = os.path.dirname(lisp.buffer_file_name()) includes = [] j = cwd while j!="/": p = os.path.join(j,".lemacs") if os.path.isfile(p): includes+=parse_lemacs(p)['include'] j = os.path.join(os.path.split(j)[:-1])[0] cpp.parse_from_includes(this_text,cwd = cwd,inclDIRS = includes) lisp.message("Loaded auto-completion data!")
def entry_search(regexp): """ search for org record, which is generated from the bibtex entry that contant given regexp. """ def bibtex_find(bib, regexp): for content in bib.values(): if re.search(regexp, content, re.I): return True keys = map(lambda x: x['id'], [x for x in bibs if bibtex_find(x, regexp)]) if len(keys) != 0: regexp = '' for key in keys: regexp += (key + '|') lisp.igrep('grep -E', regexp[:len(regexp)-1], org_path + '*.org') else: lisp.message('Not find bibtex entry')
def publish_XMLRPC_Server(): lisp.switch_to_buffer("*Messages*") # lisp.delete_other_window() lisp.message("XML RPC Started on port 9000. Ctrl-G to stop") server=SimpleXMLRPCServer(("127.0.0.1",9000)) # We will allow dotted names: server.register_function(closeConnection,"closeConnection") server.register_instance(lisp, True) #server.serve_forever() globals()['closeConnectionFlag']=False while globals()['closeConnectionFlag']==False: server.handle_request() lisp.message("Connection closed")
def publish_XMLRPC_Server(): lisp.switch_to_buffer("*Messages*") # lisp.delete_other_window() lisp.message("XML RPC Started on port 9000. Ctrl-G to stop") server = SimpleXMLRPCServer(("127.0.0.1", 9000)) # We will allow dotted names: server.register_function(closeConnection, "closeConnection") server.register_instance(lisp, True) #server.serve_forever() globals()['closeConnectionFlag'] = False while globals()['closeConnectionFlag'] == False: server.handle_request() lisp.message("Connection closed")
def pycomplete(s, fname=None, imports=None, debug=False): '''Display completion in Emacs window''' if not s: return '' # changes to where the file is if fname: os.chdir(os.path.dirname(fname)) completions = _get_all_completions(s, imports) completions.sort(key=lambda x: len(x), reverse=True) dots = s.split('.') result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == '' or result not in completions: if completions: if debug: width = 80 else: width = lisp.window_width() - 2 column = width / COLWIDTH white = ' ' * COLWIDTH msg = '' counter = 0 for completion in completions : if len(completion) < COLWIDTH: msg += completion + white[len(completion):] counter += 1 else : msg += completion + white[len(completion) - COLWIDTH:] counter += 2 if counter >= column: counter = 0 msg += '\n' else: msg = 'no completions!' if debug: return set(completions) else: lisp.message(msg) return result
def pycomplete(s, fname=None, imports=None, debug=False): '''Display completion in Emacs window''' if not s: return '' # changes to where the file is if fname: os.chdir(os.path.dirname(fname)) completions = _get_all_completions(s, imports) completions.sort(key=lambda x: len(x), reverse=True) dots = s.split('.') result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == '' or result not in completions: if completions: if debug: width = 80 else: width = lisp.window_width() - 2 column = width / COLWIDTH white = ' ' * COLWIDTH msg = '' counter = 0 for completion in completions: if len(completion) < COLWIDTH: msg += completion + white[len(completion):] counter += 1 else: msg += completion + white[len(completion) - COLWIDTH:] counter += 2 if counter >= column: counter = 0 msg += '\n' else: msg = 'no completions!' if debug: return set(completions) else: lisp.message(msg) return result
def read_glossaries(file=""): import re ifile = open("/home/bro/master/master_opp/oppgave/glossaries.tex", 'r') text = ifile.read() ifile.close() acr_pattern = re.compile( r""" \\newacronym{(?P<id>[^}]*)}{(?P<short>[^}]*)}{(?P<long>[^}]*)} """, re.VERBOSE | re.MULTILINE) acronyms = [] for match in acr_pattern.finditer(text): v = "(%s) (%s) (%s)\n" % (match.group("id"), match.group("short"), match.group("long")) lisp.message("Acronym: '%s'" % v) acronyms.append(match.group("id")) lisp._eval('(LaTeX-add-glossaries \"%s\")' % "\" \"".join(acronyms))
def pop_mark(self): marker_ring = self.get('marker_ring') if lisp.ring_empty_p(marker_ring): self.message("There are no more marked buffers in \ the rope-marker-ring") else: oldbuf = lisp.current_buffer() marker = lisp.ring_remove(marker_ring, 0) marker_buffer = lisp.marker_buffer(marker) if marker_buffer is None: lisp.message("The marked buffer has been deleted") return marker_point = lisp.marker_position(marker) lisp.set_buffer(marker_buffer) lisp.goto_char(marker_point) #Kill that marker so it doesn't slow down editing. lisp.set_marker(marker, None, None) if not lisp.eq(oldbuf, marker_buffer): lisp.switch_to_buffer(marker_buffer)
def pexec(): global glob start = time.time() remember_where = lisp.point() block_begin, block_end, content = get_block_content("\n","\n") if "=" in content or "import" in content: c = compile(source=content,filename="",mode="single") eval(c,glob) else: c = compile(source=content,filename="",mode="eval") res = eval(c,glob) lisp.forward_line(2) bb1, be2, bc2 = get_block_content("\n","\n") lisp.delete_region(bb1,be2) lisp.insert("\n") lisp.insert(str(res)) lisp.goto_char(remember_where) elapsed = (time.time() - start) lisp.message("Ran in " + str(elapsed) + " seconds")
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()
def pycomplete(s, imports=None, debug=False): """Display completion in Emacs window""" completions = _get_all_completions(s, imports) dots = s.split(".") result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == "": if completions: if debug: width = 80 else: width = lisp.window_width() - 2 column = width / 20 white = " " * 20 msg = "" counter = 0 for completion in completions: if len(completion) < 20: msg += completion + white[len(completion):] counter += 1 else: msg += completion + white[len(completion) - 20:] counter += 2 if counter >= column: counter = 0 msg += '\n' else: msg = "no completions!" if debug: print msg else: lisp.message(msg) return result
def pycomplete(s, fname=None, imports=None, debug=False): '''Display completion in Emacs window''' completions = _get_all_completions(s, fname, imports) dots = s.split('.') result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == '' or result not in completions: if completions: if debug: width = 80 else: width = lisp.window_width() - 2 column = width / COLWIDTH white = ' ' * COLWIDTH msg = '' counter = 0 for completion in completions : if len(completion) < COLWIDTH: msg += completion + white[len(completion):] counter += 1 else : msg += completion + white[len(completion) - COLWIDTH:] counter += 2 if counter >= column: counter = 0 msg += '\n' else: msg = 'no completions!' if debug: print msg else: lisp.message(msg) return result
def ask_for_style(self): """\ Request the style interactively, using the minibuffer. """ language = quality = type = None while language is None: lisp.message("\ Box language is 100-none, 200-/*, 300-//, 400-#, 500-;, 600-%%") key = lisp.read_char() if key >= ord('0') and key <= ord('6'): language = key - ord('0') while quality is None: lisp.message("\ Box quality/width is 10-simple/1, 20-rounded/2, 30-starred/3 or 40-starred/4") key = lisp.read_char() if key >= ord('0') and key <= ord('4'): quality = key - ord('0') while type is None: lisp.message("\ Box type is 1-opened, 2-half-single, 3-single, 4-half-double or 5-double") key = lisp.read_char() if key >= ord('0') and key <= ord('5'): type = key - ord('0') return 100 * language + 10 * quality + type
def show(self, level, msg): start = int(time.time() - self.startTime) mx = str(start) + " <" + level + "> PY " + self.category + " " + msg lisp.message(mx)
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) # 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")
def message(message): lisp.message(message.replace('%', '%%'))
def t(): lisp.message(msg) lisp.set_buffer("*LogBuffer*") lisp.goto_line(lisp.point_max()) lisp.insert(msg+"\n")
def help_on_region(): """Evaluates the current region as a Python expression and provides you with context-sensitive help on the result. If the result of the expression is a module, function, class, or anything with a docstring, the documentation for it will be placed in a new buffer called 'Python documentation'. If the result of the expression is a dictionary, its keys will be listed in the minibuffer. If the expression is followed by a period ('.'), this function will work somewhat similarly to the 'autocomplete' mechanism of an IDE: it will inspect the result of the expression and present you with a list of members from which you can select. The item you select will be inserted at the cursor location (i.e., after the '.'). Note that this function actually evaluates the text denoted by the given region, so if any of the functions have side effects, they will manifest themselves!""" text = get_region() if text[-1] == '.': dot_used = 1 text = text[0:-1] else: dot_used = 0 try: obj = eval(text, _py_globals) except Exception: lisp.message("Can't evaluate that region.") return import types if isinstance(obj, int) or \ isinstance(obj, float): lisp.message("Target is a number.") return docs = getattr(obj, '__doc__') if docs == None: docs = "" import inspect try: import autoimp if isinstance(obj, autoimp._RecursiveLazyModule): # Force the lazy module to load its 'real' module obj.__help__() # Have the object point to the real module, not the # lazy proxy. obj = obj._autoimp_lib except ImportError: pass if inspect.isbuiltin(obj): insert_in_other_buffer("Python documentation", docs) #lisp.message(docs) return if inspect.isfunction(obj) or inspect.ismethod(obj): out = text + inspect.formatargspec(*inspect.getargspec(obj)) out += "\n\n" + docs insert_in_other_buffer("Python documentation", out) #lisp.message(out) return if isinstance(obj, dict): if dot_used: m = autocomplete_member("Enter dictionary method name:", inspect.getmembers(obj)) lisp.insert(m) else: out = "Target is a dictionary. Keys are:\n\n" out += list_items(list(obj.keys())) lisp.message(out) return elif isinstance(obj, list) or isinstance(obj, tuple): if dot_used: m = autocomplete_member("Enter list/tuple method name:", inspect.getmembers(obj)) lisp.insert(m) else: out = "Target is a list. Elements are:\n\n" out += list_items(obj) lisp.message(out) return if not dot_used: #lisp.message(docs + "\n\n") insert_in_other_buffer("Python documentation", docs) return if inspect.ismodule(obj): m = autocomplete_member("Enter module attribute name:", inspect.getmembers(obj)) lisp.insert(m) return klass = obj try: klass = getattr(obj, '__class__') prompt = "Enter attribute name for instance of class %s: " % \ klass.__name__ except AttributeError: prompt = "Enter attribute name: " m = autocomplete_member(prompt, inspect.getmembers(klass)) lisp.insert(m)