コード例 #1
0
ファイル: bib2org.py プロジェクト: binbao/emacs
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')
コード例 #2
0
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])
コード例 #3
0
def _switchToConsole():
    consolebuf = lisp.get_buffer_create("BicycleRepairManConsole")
    lisp.switch_to_buffer_other_window(consolebuf)
    lisp.compilation_mode("BicycleRepairMan")
    lisp.erase_buffer()
    lisp.insert("Bicycle Repair Man\n")
    lisp.insert("(Hint: Press Return a Link)\n")
コード例 #4
0
ファイル: pym.py プロジェクト: caseboy01/myemacs
def bow():
    """Break a region replacing all whitespace with newlines.

    Originally an example in Pymacs' README."""

    region = cut_region()
    lisp.insert('\n'.join(region.split()))
コード例 #5
0
ファイル: flymake-pyfixers.py プロジェクト: choppsv1/emacs.d
def fixer_equals_none (unused_error, unused_errtext):
    start, end, line = get_line_string()
    newline = re.sub(r"==\s*None", r"is None", line)
    newline = re.sub(r"!=\s*None", r"is not None", newline)
    if newline != line:
        lisp.delete_region(start, end)
        lisp.insert(newline)
コード例 #6
0
    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))
コード例 #7
0
ファイル: rebox.py プロジェクト: stephencreighton/emacs_libs
    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))
コード例 #8
0
ファイル: githist.py プロジェクト: saiftech1/kod
def show_version(num):
    print "Getting this version ago:" + str(num)
    dot_git_dir = find_dot_git()
    os.chdir(dot_git_dir)

    fname = lisp.buffer_file_name()

    # subtract the .git location from the beginning part of the
    # full path because git show does not like it
    print "fname=" + fname
    print "dot_git_dir=" + dot_git_dir
    suitable_dir_for_git_show = re.sub(dot_git_dir, "", fname)
    print suitable_dir_for_git_show

    # also get rid of the first /
    suitable_dir_for_git_show = re.sub("^/", "", suitable_dir_for_git_show)
    print suitable_dir_for_git_show

    cmd = "git show master~" + str(num) + ":" + suitable_dir_for_git_show
    print cmd

    list = run_command(cmd)

    lisp.switch_to_buffer_other_window(cmd)
    for item in list:
        lisp.insert(item)
コード例 #9
0
ファイル: deascify.py プロジェクト: verawatk/kod
def convert():
    remember_where = lisp.point()
    block_begin, block_end, content = get_block_content("\n\n", "\n\n")

    # alttaki listeye dokunulmamasi istenen kelimeler tek ogeli
    # tuple olarak yazilir, ("kelime",) gibi. eger degisim isteniyorsa
    # ("kelime","degisim") olarak bir tuple eklenir.
    r_list = [("verisi", ), ("Calculus", ), ("AIC", ), ("estimator", ),
              (" ise", ), ("kontur", ), ("ODE", ), ("Oklit", u'Öklit'),
              ("karekok", u'karekök'), ("kismi", u'kısmi'), ("integral", ),
              ("oldugu", u'olduğu'), ("parcaci", u"parçacı"),
              ("acilimi", u'açılımı'), ("acilim", u'açılım'),
              ("acisini", u'açısını'), ("acisi", u'açısı'), ("aci", u'açı'),
              ("minimize", ), ("gayri", u'gayrı'), ("Pandas", ),
              ("algoritma", ), ("gayri", u'gayrı'), ("sigma", ),
              ("volatility", ), ("matris", ), ("frac", "frac"),
              ("sonum", u"sönüm"), ("eksen", ), ("sonusur", u"sonuşur"),
              ("amaci", u"amacı"), ("amacimiz", u"amacımız"),
              ("sarsim", u"sarsım"), ("Sarsim", u"Sarsım"), (u"olduğu", )]

    r_list_coded = []
    for x in r_list:
        r_list_coded.append((x[0], str(int(random.random() * 1000000))))
    for x in r_list_coded:
        content = content.replace(x[0], x[1])
    result = to_tr(content)
    for x in r_list_coded:
        result = result.replace(x[1], x[0])
    for x in r_list:
        if len(x) == 2: result = result.replace(x[0], x[1])

    lisp.delete_region(block_begin, block_end)
    lisp.insert(result)
    lisp.goto_char(remember_where)
コード例 #10
0
ファイル: pym.py プロジェクト: Airead/airemacs.d
def bow():
    """Break a region replacing all whitespace with newlines.

    Originally an example in Pymacs' README."""

    region = cut_region()
    lisp.insert('\n'.join(region.split()))
コード例 #11
0
def _switchToConsole():
    consolebuf = lisp.get_buffer_create("BicycleRepairManConsole")
    lisp.switch_to_buffer_other_window(consolebuf)
    lisp.compilation_mode("BicycleRepairMan")
    lisp.erase_buffer()
    lisp.insert("Bicycle Repair Man\n")
    lisp.insert("(Hint: Press Return a Link)\n")
コード例 #12
0
ファイル: pastemacs.py プロジェクト: tabuchid/dotfiles
def insert_by_id(paste_id):
    """Fetches paste with `paste_id` and inserts it into current buffer"""
    paste = lodgeit.get_paste_by_id(paste_id)
    if paste:
        lisp.insert(paste.code)
    else:
        lisp.error('There is no paste with id {0}'.format(paste_id))
コード例 #13
0
    def _make_buffer(self, name, contents, empty_goto=True, switch=False,
                     window='other', modes=[], fit_lines=None):
        """Make an emacs buffer

        `window` can be one of `None`, 'current' or 'other'.
        """
        new_buffer = lisp.get_buffer_create(name)
        lisp.set_buffer(new_buffer)
        lisp.toggle_read_only(-1)
        lisp.erase_buffer()
        if contents or empty_goto:
            lisp.insert(contents)
            for mode in modes:
                lisp[mode + '-mode']()
            lisp.buffer_disable_undo(new_buffer)
            lisp.toggle_read_only(1)
            if switch:
                if window == 'current':
                    lisp.switch_to_buffer(new_buffer)
                else:
                    lisp.switch_to_buffer_other_window(new_buffer)
                lisp.goto_char(lisp.point_min())
            elif window == 'other':
                new_window = lisp.display_buffer(new_buffer)
                lisp.set_window_point(new_window, lisp.point_min())
                if fit_lines and lisp.fboundp(lisp['fit-window-to-buffer']):
                    lisp.fit_window_to_buffer(new_window, fit_lines)
                    lisp.bury_buffer(new_buffer)
        return new_buffer
コード例 #14
0
    def _make_buffer(self,
                     name,
                     contents,
                     empty_goto=True,
                     switch=False,
                     window='other',
                     modes=[],
                     fit_lines=None):
        """Make an emacs buffer

        `window` can be one of `None`, 'current' or 'other'.
        """
        new_buffer = lisp.get_buffer_create(name)
        lisp.set_buffer(new_buffer)
        lisp.toggle_read_only(-1)
        lisp.erase_buffer()
        if contents or empty_goto:
            lisp.insert(contents)
            for mode in modes:
                lisp[mode + '-mode']()
            lisp.buffer_disable_undo(new_buffer)
            lisp.toggle_read_only(1)
            if switch:
                if window == 'current':
                    lisp.switch_to_buffer(new_buffer)
                else:
                    lisp.switch_to_buffer_other_window(new_buffer)
                lisp.goto_char(lisp.point_min())
            elif window == 'other':
                new_window = lisp.display_buffer(new_buffer)
                lisp.set_window_point(new_window, lisp.point_min())
                if fit_lines and lisp.fboundp(lisp['fit-window-to-buffer']):
                    lisp.fit_window_to_buffer(new_window, fit_lines)
                    lisp.bury_buffer(new_buffer)
        return new_buffer
コード例 #15
0
def insert_by_id(paste_id):
    """Fetches paste with `paste_id` and inserts it into current buffer"""
    paste = lodgeit.get_paste_by_id(paste_id)
    if paste:
        lisp.insert(paste.code)
    else:
        lisp.error('There is no paste with id %s', paste_id)
コード例 #16
0
ファイル: githist.py プロジェクト: chyojn/kod
def show_version(num):
    print "Getting this version ago:" + str(num)
    dot_git_dir = find_dot_git()
    os.chdir(dot_git_dir)
    
    fname=lisp.buffer_file_name()
    
    # subtract the .git location from the beginning part of the 
    # full path because git show does not like it
    print "fname="+fname
    print "dot_git_dir="+dot_git_dir
    suitable_dir_for_git_show = re.sub(dot_git_dir, "", fname)
    print suitable_dir_for_git_show

    # also get rid of the first / 
    suitable_dir_for_git_show = re.sub("^/", "", suitable_dir_for_git_show)
    print suitable_dir_for_git_show
    
    cmd = "git show master~" + str(num) + ":" + suitable_dir_for_git_show
    print cmd
    
    list = run_command(cmd)
    
    lisp.switch_to_buffer_other_window(cmd)
    for item in list:
        lisp.insert(item)
コード例 #17
0
ファイル: deascify.py プロジェクト: dean-wong/kod
def convert():
    remember_where = lisp.point()
    block_begin, block_end, content = get_block_content("\n\n","\n\n")

    # alttaki listeye dokunulmamasi istenen kelimeler tek ogeli
    # tuple olarak yazilir, ("kelime",) gibi. eger degisim isteniyorsa
    # ("kelime","degisim") olarak bir tuple eklenir. 
    r_list = [("verisi",),("Calculus",),("AIC",),("estimator",),(" ise",),
              ("kontur",),("ODE",),("Oklit",u'Öklit'),("karekok",u'karekök'),
              ("kismi", u'kısmi'),("integral",),("oldugu",u'olduğu'),
              ("acilimi",u'açılımı'),("acilim",u'açılım'),("aci",u'açı'),
              ("minimize",),("gayri",u'gayrı'),("Pandas",),("algoritma",),
              ("gayri",u'gayrı'),("sigma",),("volatility",),("matris",)]
              
    r_list_coded = []
    for x in r_list: r_list_coded.append((x[0],str(int(random.random() * 1000000))))
    for x in r_list_coded: content = content.replace(x[0],x[1])
    result = to_tr(content)    
    for x in r_list_coded: result = result.replace(x[1],x[0])              
    for x in r_list:
        if len(x)==2: result = result.replace(x[0],x[1])              
              
    lisp.delete_region(block_begin, block_end)
    lisp.insert(result)
    lisp.goto_char(remember_where)
コード例 #18
0
ファイル: interface.py プロジェクト: FredSanders/emacs.d
 def _insert_import(self, name, module):
     lineno = self.autoimport.find_insertion_line(self.source)
     current = lisp.point()
     lisp.goto_line(lineno)
     newimport = 'from %s import %s\n' % (module, name)
     lisp.insert(newimport)
     lisp.goto_char(current + len(newimport))
コード例 #19
0
def from_rest():
    text = get_text()
    parts = docutils.core.publish_parts(text, writer=Writer())

    lisp.weblogger_start_entry()
    lisp.insert(parts['title'])
    lisp.goto_char(lisp.point_max())
    lisp.insert(parts['body'])
コード例 #20
0
ファイル: pym.py プロジェクト: caseboy01/myemacs
def dos2unix():
    """Remove DOS line endings from a region.
    """
    # Save undo state so we can roll everything into a single operation for undo
    checkpoint = lisp.buffer_undo_list.value()
    region = cut_region('list')
    lisp.insert('\n'.join(region) + '\n')
    # Collapse all operations into a single one, for Undo.
    clean_undo_after(checkpoint)
コード例 #21
0
ファイル: interface.py プロジェクト: FredSanders/emacs.d
 def _apply_assist(self, assist):
     if ' : ' in assist:
         name, module = assist.rsplit(' : ', 1)
         lisp.delete_region(self.starting_offset + 1, self.offset + 1)
         lisp.insert(name)
         self._insert_import(name, module)
     else:
         lisp.delete_region(self.starting_offset + 1, self.offset + 1)
         lisp.insert(assist)
コード例 #22
0
ファイル: pym.py プロジェクト: Airead/airemacs.d
def dos2unix():
    """Remove DOS line endings from a region.
    """
    # Save undo state so we can roll everything into a single operation for undo
    checkpoint = lisp.buffer_undo_list.value()
    region = cut_region('list')
    lisp.insert('\n'.join(region)+'\n')
    # Collapse all operations into a single one, for Undo.
    clean_undo_after(checkpoint)
コード例 #23
0
ファイル: jhr.py プロジェクト: joehakimrahme/.emacs.d
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)
コード例 #24
0
ファイル: __init__.py プロジェクト: jaouad00/jarvis-1
    def __call__(self, *args):
        s = open(self.commandfilename).read()
        template = jinja2.Template(s)

        kwargs = {}
        for i, a in enumerate(args):
            kwargs[self.variables[i]] = a

        s = template.render(**kwargs)
        lisp.insert(s)
コード例 #25
0
def new_buffer_from_paste(paste):
    """Creates a new buffer from `paste`"""
    lisp.switch_to_buffer('paste %s' % paste.id)
    lisp.erase_buffer()
    lisp.insert(paste.code)
    # simple guessing of the buffer mode
    # XXX: is there a better way?
    # FIXME: do at least a bit of error handling and check, if there is such a mode
    mode = lisp['%s-mode' % paste.language]
    mode()
コード例 #26
0
ファイル: pastemacs.py プロジェクト: tabuchid/dotfiles
def new_buffer_from_paste(paste):
    """Creates a new buffer from `paste`"""
    lisp.switch_to_buffer('paste {0.id}'.format(paste))
    lisp.erase_buffer()
    lisp.insert(paste.code)
    # simple guessing of the buffer mode
    # XXX: is there a better way?
    # FIXME: do at least a bit of error handling and check, if there is such a mode
    mode = lisp['{0.language}-mode'.format(paste)]
    mode()
コード例 #27
0
ファイル: __init__.py プロジェクト: alendit/jarvis
    def __call__(self, *args):
        s = open(self.commandfilename).read()
        template = jinja2.Template(s)

        kwargs = {}
        for i, a in enumerate(args):
            kwargs[self.variables[i]] = a

        s = template.render(**kwargs)
        lisp.insert(s)
コード例 #28
0
ファイル: ipython-md.py プロジェクト: ing7t/kod
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")
コード例 #29
0
ファイル: pymdev.py プロジェクト: emacsvsvi/linux-dev-env
def insert_in_other_buffer(bufname, text):
     """Creates/erases a buffer with the given name, opens it in a
     separate visible  pane, and pastes the given text into it."""
     
     lisp.get_buffer_create(bufname)
     lisp.display_buffer(bufname, 1)
     old_buf = lisp.current_buffer()
     lisp.set_buffer(bufname)
     lisp.erase_buffer()
     lisp.insert(text)
     lisp.set_buffer(old_buf)
コード例 #30
0
def insert_in_other_buffer(bufname, text):
    """Creates/erases a buffer with the given name, opens it in a
     separate visible  pane, and pastes the given text into it."""

    lisp.get_buffer_create(bufname)
    lisp.display_buffer(bufname, 1)
    old_buf = lisp.current_buffer()
    lisp.set_buffer(bufname)
    lisp.erase_buffer()
    lisp.insert(text)
    lisp.set_buffer(old_buf)
コード例 #31
0
 def find_references(self):
     lisp.save_some_buffers()
     filename = lisp.buffer_file_name()
     line, col = _getCoords()
     refs = brmctx.findReferencesByCoordinates(filename, line, col)
     _switchToConsole()
     numRefs = 0
     for ref in refs:
         _insertRefLineIntoConsole(ref)
         numRefs += 1
     lisp.insert("Done - %d refs found\n" % numRefs)
コード例 #32
0
ファイル: ipython-md.py プロジェクト: verawatk/kod
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")
コード例 #33
0
 def find_references(self):
     lisp.save_some_buffers()
     filename = lisp.buffer_file_name()
     line,col = _getCoords()
     refs = brmctx.findReferencesByCoordinates(filename,line,col)
     _switchToConsole()
     numRefs = 0
     for ref in refs:
         _insertRefLineIntoConsole(ref)
         numRefs +=1
     lisp.insert("Done - %d refs found\n"%numRefs)
コード例 #34
0
ファイル: manglers.py プロジェクト: markwatson/Emacs.d
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)
コード例 #35
0
ファイル: pym.py プロジェクト: caseboy01/myemacs
def insert_text(text, offset=0):
    """Insert text in buffer and move cursor to a certain offset.

    If called with no offset, leaves the cursor at the current position."""

    # save undo state so we can roll everything into a single operation for undo
    checkpoint = lisp.buffer_undo_list.value()
    user_pos = lisp.point()
    lisp.insert(text)
    lisp.goto_char(user_pos + offset)
    # Collapse all operations into a single one, for Undo.
    clean_undo_after(checkpoint)
コード例 #36
0
ファイル: pym.py プロジェクト: Airead/airemacs.d
def insert_text(text,offset=0):
    """Insert text in buffer and move cursor to a certain offset.

    If called with no offset, leaves the cursor at the current position."""

    # save undo state so we can roll everything into a single operation for undo
    checkpoint = lisp.buffer_undo_list.value()
    user_pos = lisp.point()
    lisp.insert(text)
    lisp.goto_char(user_pos+offset)
    # Collapse all operations into a single one, for Undo.
    clean_undo_after(checkpoint)
コード例 #37
0
def find_descendants(): 
    """
    retrieves descendants of class at point by running a Unix find. 
    simple huh?
    """
    fname=lisp.buffer_file_name()
    a = Project(fname)
    thing, start = thing_at_point(RIGHT1, LEFT1)
    descs = a.find_all_descendants(thing)
    ready_output()
    
    for item in descs:
        lisp.insert(item)
コード例 #38
0
ファイル: interface.py プロジェクト: FredSanders/emacs.d
 def code_assist(self, prefix):
     names = self._calculate_proposals()
     if prefix is not None:
         arg = lisp.prefix_numeric_value(prefix)
         if arg == 0:
             arg = len(names)
         common_start = self._calculate_prefix(names[:arg])
         lisp.insert(common_start[self.offset - self.starting_offset:])
         self._starting = common_start
         self._offset = self.starting_offset + len(common_start)
     prompt = 'Completion for %s: ' % self.expression
     result = lisputils.ask_values(prompt, names,
                                   starting=self.starting, exact=None)
     self._apply_assist(result)
コード例 #39
0
ファイル: unitdiscover.py プロジェクト: pdee/pdee
def discover(directory):
    directory = os.path.expanduser(directory) # The tilde does not work with os.chdir
    os.chdir(directory)
    
    # Discovering tests using unittest framework
    loader = TestLoader()
    tests = loader.discover(directory, top_level_dir=directory)
    result = EmacsTestResult()
    
    # Create a buffer (if it not exists) and put the formatted results
    # inside it
    let = Let()
    lisp.get_buffer_create("unittest")
    let.push_excursion()
    lisp.set_buffer("unittest")
    lisp.erase_buffer()
    tests.run(result)
    lisp.insert("\n")
    lisp.insert("Errors:\n")
    for test, traceback in result.errors:
        lisp.insert(str(test))
        lisp.insert(traceback)
    let.pop_excursion()
    
    lisp.pop_to_buffer("unittest")
    lisp.compilation_mode()
    lisp.beginning_of_buffer()
コード例 #40
0
ファイル: flymake-pyfixers.py プロジェクト: choppsv1/emacs.d
def fixer_remove_trailing_ws(unused_error, unused_text):
    start, end, line = get_line_string()
    m = re.match(r"^(.*\S+)?\s*$", line)
    if not m:
        #print("NO MATCH")
        return
    #print("MATCH")
    if m.group(1):
        newline = m.group(1)
    else:
        newline = ""
    if newline != line:
        lisp.delete_region(start, end)
        lisp.insert(newline)
コード例 #41
0
def discover(directory):
    directory = os.path.expanduser(
        directory)  # The tilde does not work with os.chdir
    os.chdir(directory)

    # Discovering tests using unittest framework
    loader = TestLoader()
    tests = loader.discover(directory, top_level_dir=directory)
    result = EmacsTestResult()

    # Create a buffer (if it not exists) and put the formatted results
    # inside it
    let = Let()
    lisp.get_buffer_create("unittest")
    let.push_excursion()
    lisp.set_buffer("unittest")
    lisp.erase_buffer()
    tests.run(result)
    lisp.insert("\n")
    lisp.insert("Errors:\n")
    for test, traceback in result.errors:
        lisp.insert(str(test))
        lisp.insert(traceback)
    let.pop_excursion()

    lisp.pop_to_buffer("unittest")
    lisp.compilation_mode()
    lisp.beginning_of_buffer()
コード例 #42
0
def pick_method():
    '''
    pick the whole line from the list of function calls (completions)
    '''
    print "in pick method"
    thing, start = thing_at_point(RIGHT2, LEFT2)
    prev_buffer = os.environ['BUFFER']
    print "-"+prev_buffer+"-"
    lisp.kill_buffer(lisp.get_buffer("*PyJde*"))
    lisp.switch_to_buffer(prev_buffer)
    lisp.insert(thing)
    pos = lisp.point()
    print "pos="+(str(pos-1))
    lisp.goto_char(pos-1)
    lisp.delete_other_windows()
コード例 #43
0
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 + ";")
コード例 #44
0
ファイル: devonthink.py プロジェクト: deactivated/Devonmacs
def url(text):
    opts = quicksearch(text)
    if opts:
        opts_map = {n: u for u, n in opts}
        sel = lisp.ido_completing_read("Choose: ", [n for u, n in opts])
    if opts and sel:
        url = "x-devonthink-item://%s" % opts_map[sel]

    mode = lisp.major_mode.value()
    if mode == lisp["org-mode"]:
        link = "[[%s][%s]]" % (url, sel)
    elif mode == lisp["markdown-mode"]:
        link = "[%s](%s)" % (url, sel)
    else:
        link = url
    lisp.insert(link)
コード例 #45
0
ファイル: deascify.py プロジェクト: melampyge/kod
def convert():
    remember_where = lisp.point()
    block_begin, block_end, content = get_block_content("\n\n","\n\n")


    content = content.replace("verisi","WWXXD1")
    content = content.replace("Calculus","WWXXD2")
    content = content.replace("AIC","WWXXD3")
    content = content.replace("estimator","WWXXD5")
    content = content.replace(" ise","WWXXD7")
    content = content.replace("kontur","WWXXD8")
    content = content.replace("ODE","WWXXD9")
    content = content.replace("Oklit","WWXXDx3")
    content = content.replace("karekok","WWXXDx4")
    content = content.replace("kismi","WWXXDx5")
    content = content.replace("integral","WWXXDx7")
    content = content.replace("acilimi","WWXXDx8")
    content = content.replace(" aci","WWXXDy1")
    content = content.replace("gayri","WWXXDy2")
    content = content.replace("oldugu","WWXXDy3")
    content = content.replace("Pandas","WWXXDy4")
    content = content.replace("algoritma","WWXXDy5")
    content = content.replace("minimize","WWXXDy6")

    result = to_tr(content)
    result = result.replace("WWXXD1","verisi")
    result = result.replace("WWXXD2","Calculus")
    result = result.replace("WWXXD3","AIC")
    result = result.replace("WWXXD5","estimator")
    result = result.replace("WWXXD7"," ise" )
    result = result.replace("WWXXD8","kontur" )
    result = result.replace("WWXXD9","ODE" )
    result = result.replace('WWXXDx3',u'Öklit' )
    result = result.replace('WWXXDx4',u'karekök' )
    result = result.replace('WWXXDx5',u'kısmi' )
    result = result.replace('WWXXDx7',u'integral' )
    result = result.replace('WWXXDx8',u'acılımı' )
    result = result.replace('WWXXDy1',u' açı' )
    result = result.replace('WWXXDy2',u' gayrı' )
    result = result.replace('WWXXDy3',u'olduğu' )
    result = result.replace('WWXXDy4',u'Pandas' )
    result = result.replace('WWXXDy5',u'algoritma' )
    result = result.replace('WWXXDy6',u'minimize' )

    lisp.delete_region(block_begin, block_end)
    lisp.insert(result)
    lisp.goto_char(remember_where)
コード例 #46
0
ファイル: pym.py プロジェクト: caseboy01/myemacs
def insert_indented_text(text, offset):
    """Insert indented text in buffer and move cursor to a certain offset."""

    # save undo state so we can roll everything into a single operation for undo
    checkpoint = lisp.buffer_undo_list.value()
    # figure out if we are indented or not, and adapt text accordingly
    indent_level = get_line_offset()
    if indent_level > 0:
        text = indent(text, indent_level)
    # perform actual insertion with proper cursor positioning
    offset += indent_level
    lisp.beginning_of_line()
    user_pos = lisp.point()
    lisp.insert(text)
    lisp.goto_char(user_pos + offset)
    # Collapse all operations into a single one, for Undo.
    clean_undo_after(checkpoint)
コード例 #47
0
    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)
コード例 #48
0
ファイル: githist.py プロジェクト: rumaihba/kod
def show_version(num):
    print "Getting this version ago:" + str(num)
    dot_git_dir = find_dot_git()
    os.chdir(dot_git_dir)

    fname = lisp.buffer_file_name()

    # subtract the .git location from the beginning part of the
    # full path because git show does not like it
    suitable_dir_for_git_show = re.sub(dot_git_dir, "", fname)

    # also get rid of the first /
    suitable_dir_for_git_show = re.sub("^/", "", suitable_dir_for_git_show)

    cmd = "git show %s~%d:%s" % (branch(), num, suitable_dir_for_git_show)

    res = run_command(cmd)
    lisp.switch_to_buffer_other_window(cmd)
    for item in res:
        lisp.insert(item)
コード例 #49
0
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()
コード例 #50
0
def show():
    b, e, res = get_block_content("$$", "$$")
    d = hash(res)
    foutsimple = "_preview/f-%d.png" % d
    if os.path.isfile(foutsimple): return  # do nothing
    latex(res)
    curr_dir = os.path.dirname(lisp.buffer_file_name())
    fout = "%s/_preview/f-%d.png" % (curr_dir, d)
    shutil.copy(dir + "\standalone.png", fout)

    remem = lisp.point()
    lisp.goto_char(e)
    lisp.forward_line(1)
    lisp.beginning_of_line()
    bb = lisp.point()
    lisp.end_of_line()
    ee = lisp.point()
    lisp.delete_region(bb, ee)
    lisp.insert("%{{" + foutsimple + "}}")
    lisp.goto_char(remem)
    lisp.iimage_mode(1)
コード例 #51
0
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)
コード例 #52
0
ファイル: __init__.py プロジェクト: caseboy01/myemacs
    def show_occurrences(self, locations):
        buffer = self._make_buffer('*rope-occurrences*', "", switch=False)
        lisp.set_buffer(buffer)
        lisp.toggle_read_only(0)

        trunc_length = len(lisp.rope_get_project_root())

        lisp.insert('List of occurrences:\n')
        for location in locations:
            code_line = self.read_line_from_file(location.filename, location.lineno).rstrip()
            filename = location.filename[trunc_length:]
            lineno = str(location.lineno)
            offset = str(location.offset)

            lisp.insert(filename + ":" + lineno + ":" + code_line + " " + offset)

            beginning = lisp.line_beginning_position()
            end = beginning + len(filename)

            lisp.add_text_properties(beginning, end, [lisp.face, lisp.button])
            lisp.add_text_properties(beginning, end, [lisp.mouse_face, lisp.highlight,
                                                      lisp.help_echo, "mouse-2: visit this file in other window"])

            lisp.insert("\n")

        lisp.toggle_read_only(1)

        lisp.set(lisp["next-error-function"], lisp.rope_occurrences_next)
        lisp.local_set_key('\r', lisp.rope_occurrences_goto)
        lisp.local_set_key((lisp.mouse_1,), lisp.rope_occurrences_goto)
        lisp.local_set_key('q', lisp.delete_window)
コード例 #53
0
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)
コード例 #54
0
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")
コード例 #55
0
def display_results(end_block, res):
    remem = lisp.point()
    res = res.replace("\r", "")
    lisp.goto_char(end_block)
    verb_begin = None
    # if there is output block, remove it whether there output or not
    # because it will be replaced anyway if something exists
    if verb_exists():
        verb_begin, verb_end, content = get_block_content("```text", "```\n")
        lisp.delete_region(verb_begin, verb_end)
        lisp.goto_char(remem)

    # now if there _is_ output, then go to beginning of old verbatim
    # output (if removed), if not, this is brand new output, move
    # down 2 lines, insert the output
    if verb_begin:
        lisp.goto_char(verb_begin)
    else:
        lisp.forward_line(1)
    lisp.insert("```text\n")
    lisp.insert(res)
    lisp.insert("```\n")
コード例 #56
0
ファイル: rebox.py プロジェクト: caseboy01/myemacs
    def find_comment(self):
        """\
Find and return the limits of the block of comments following or enclosing
the cursor, or return an error if the cursor is not within such a block
of comments.  Extend it as far as possible in both directions.
"""
        let = Let().push_excursion()
        try:
            # Find the start of the current or immediately following comment.
            lisp.beginning_of_line()
            lisp.skip_chars_forward(' \t\n')
            lisp.beginning_of_line()
            if not language_matcher[0](self.remainder_of_line()):
                temp = lisp.point()
                if not lisp.re_search_forward('\\*/', None, lisp.t):
                    lisp.error("outside any comment block")
                lisp.re_search_backward('/\\*')
                if lisp.point() > temp:
                    lisp.error("outside any comment block")
                temp = lisp.point()
                lisp.beginning_of_line()
                lisp.skip_chars_forward(' \t')
                if lisp.point() != temp:
                    lisp.error("text before start of comment")
                lisp.beginning_of_line()
            start = lisp.point()
            language = guess_language(self.remainder_of_line())
            # Find the end of this comment.
            if language == 2:
                lisp.search_forward('*/')
                if not lisp.looking_at('[ \t]*$'):
                    lisp.error("text after end of comment")
            lisp.end_of_line()
            if lisp.eobp():
                lisp.insert('\n')
            else:
                lisp.forward_char(1)
            end = lisp.point()
            # Try to extend the comment block backwards.
            lisp.goto_char(start)
            while not lisp.bobp():
                if language == 2:
                    lisp.skip_chars_backward(' \t\n')
                    if not lisp.looking_at('[ \t]*\n[ \t]*/\\*'):
                        break
                    if lisp.point() < 2:
                        break
                    lisp.backward_char(2)
                    if not lisp.looking_at('\\*/'):
                        break
                    lisp.re_search_backward('/\\*')
                    temp = lisp.point()
                    lisp.beginning_of_line()
                    lisp.skip_chars_forward(' \t')
                    if lisp.point() != temp:
                        break
                    lisp.beginning_of_line()
                else:
                    lisp.previous_line(1)
                    if not language_matcher[language](
                            self.remainder_of_line()):
                        break
                start = lisp.point()
            # Try to extend the comment block forward.
            lisp.goto_char(end)
            while language_matcher[language](self.remainder_of_line()):
                if language == 2:
                    lisp.re_search_forward('[ \t]*/\\*')
                    lisp.re_search_forward('\\*/')
                    if lisp.looking_at('[ \t]*$'):
                        lisp.beginning_of_line()
                        lisp.forward_line(1)
                        end = lisp.point()
                else:
                    lisp.forward_line(1)
                    end = lisp.point()
            return start, end
        finally:
            let.pops()