示例#1
0
def get_filelist(query=None, archive=None):  # {{{1
    """ __get_filelist(query) -> list_of_notes

    Returns a list of notes. If no query is provided, all the valid filenames
    in self.save_dir are returned in a list, otherwise, return the results of
    grep or ack search for query in self.save_dir.
    """
    local_path = vim.eval("getcwd(). '/'. g:pad#local_dir")
    use_local_dir = vim.eval(
        'g:pad#local_dir') != '' and local_path != get_save_dir()
    if not query or query == "":
        files = listdir_recursive_nohidden(get_save_dir(), archive)

        if use_local_dir:
            files.extend(listdir_recursive_nohidden(local_path, archive))
    else:
        files = listdir_external(get_save_dir(), archive, query)

        if bool(int(vim.eval("g:pad#query_filenames"))):
            matches = filter(lambda i: not isdir(i) and i not in files,
                             glob(join(get_save_dir(), "*" + query + "*")))
            files.extend(matches)

        if bool(int(vim.eval("g:pad#query_dirnames"))):
            matching_dirs = filter(
                isdir, glob(join(get_save_dir(), "*" + query + "*")))
            for mdir in matching_dirs:
                files.extend(
                    filter(lambda x: x not in files,
                           listdir_recursive_nohidden(mdir, archive)))

        if use_local_dir:
            files.extend(listdir_external(local_path, archive, query))

    return files
示例#2
0
def update():
    """ Moves a note to a new location if its contents are modified.

    Called on the BufLeave event for the notes.

    """
    if not bool(int(vim.eval('exists("b:pad_modified")'))):
        return

    modified = bool(int(vim.eval("b:pad_modified")))
    can_rename = bool(int(vim.eval("g:pad#rename_files")))
    if modified and can_rename:
        _id = PadInfo(vim.current.buffer).id
        old_path = expanduser(vim.current.buffer.name)

        fs = filter(isfile, glob(expanduser(join(dirname(vim.current.buffer.name), _id)) + "*"))
        if old_path not in fs:
            if fs == []:
                new_path = expanduser(join(get_save_dir(), _id))
            else:
                exts = map(lambda i: "0" if i == "" else i[1:], map(lambda i: splitext(i)[1], fs))
                new_path = ".".join([expanduser(join(get_save_dir(), _id)), str(int(max(exts)) + 1)])
            new_path = new_path + vim.eval("g:pad#default_file_extension")
            vim.command("bw")
            move(old_path, new_path)
示例#3
0
def get_filelist(query=None, archive=None):  # {{{1
    """ __get_filelist(query) -> list_of_notes

    Returns a list of notes. If no query is provided, all the valid filenames
    in self.save_dir are returned in a list, otherwise, return the results of
    grep or ack search for query in self.save_dir.
    """
    local_path = vim.eval("getcwd(). '/'. g:pad#local_dir")
    use_local_dir = vim.eval('g:pad#local_dir') != '' and local_path != get_save_dir()
    if not query or query == "":
        files = listdir_recursive_nohidden(get_save_dir(), archive)

        if use_local_dir:
            files.extend(listdir_recursive_nohidden(local_path, archive))
    else:
        files = listdir_external(get_save_dir(), archive, query)

        if bool(int(vim.eval("g:pad#query_filenames"))):
            matches = filter(lambda i: not isdir(i) and i not in files, glob(join(get_save_dir(), "*"+query+"*")))
            files.extend(matches)

        if bool(int(vim.eval("g:pad#query_dirnames"))):
            matching_dirs = filter(isdir, glob(join(get_save_dir(), "*"+ query+"*")))
            for mdir in matching_dirs:
                files.extend(filter(lambda x: x not in files, listdir_recursive_nohidden(mdir, archive)))

        if use_local_dir:
            files.extend(listdir_external(local_path, archive, query))

    return files
示例#4
0
def set_vim_globals():
    """ Sets global vim preferences and commands.
    """
    # To update the date when files are modified
    if get_save_dir() == "":
        vim.command('echom "vim-pad: IMPORTANT: please set g:pad#dir to a valid path in your vimrc."')
        vim.command("redraw")
    else:
        vim.command('execute "au! BufEnter" printf("%s*", g:pad#dir) ":let b:pad_modified = 0"')
        vim.command('execute "au! BufWritePre" printf("%s*", g:pad#dir) ":let b:pad_modified = eval(&modified)"')
        vim.command('execute "au! BufLeave" printf("%s*", g:pad#dir) ":call pad#UpdatePad()"')

    # vim-pad pollutes the MRU.vim list quite a lot, if let alone.
    # This should fix that.
    if vim.eval('exists(":MRU")') == "2":
        mru_exclude_files = vim.eval("MRU_Exclude_Files")
        if mru_exclude_files != '':
            tail = "\|" + mru_exclude_files
        else:
            tail = ''
        vim.command("let MRU_Exclude_Files = '^" +
                join(get_save_dir(), ".*") + tail + "'")

    # we forbid writing backups of the notes
    orig_backupskip = vim.eval("&backupskip")
    vim.command("let &backupskip='" +
            ",".join([orig_backupskip, join(get_save_dir(), "*")]) + "'")
示例#5
0
def move_to_folder(path=None):
    if path is None:
        path = vim.eval("input('move to: ')")
    new_path = join(get_save_dir(), path, basename(vim.current.buffer.name))
    if not exists(join(get_save_dir(), path)):
        mkdir(join(get_save_dir(), path))
    move(vim.current.buffer.name, new_path)
    vim.command("bd")
示例#6
0
def move_to_folder(path=None):
    if path is None:
        path = vim.eval("input('move to: ')")
    new_path = join(get_save_dir(), path, basename(vim.current.buffer.name))
    if not exists(join(get_save_dir(), path)):
        mkdir(join(get_save_dir(), path))
    move(vim.current.buffer.name, new_path)
    vim.command("bd")
示例#7
0
def move_to_folder(path=None):  # {{{1
    """ Moves the selected pad to a subfolder of g:pad#dir
    """
    selected_path = get_selected_path()
    if path is None:
        path = vim.eval('input("move to: ")')
    if not exists(join(get_save_dir(), path)):
        mkdir(join(get_save_dir(), path))
    move(selected_path, join(get_save_dir(), path, basename(selected_path)))
    make_sure_dir_is_empty(path)
    vim.command("ListPads")
    if path is None:
        vim.command("redraw!")
示例#8
0
def move_to_folder(path=None):  # {{{1
    """ Moves the selected pad to a subfolder of g:pad#dir
    """
    selected_path = get_selected_path()
    if path is None:
        path = vim.eval('input("move to: ")')
    if not exists(join(get_save_dir(), path)):
        mkdir(join(get_save_dir(), path))
    move(selected_path, join(get_save_dir(), path, basename(selected_path)))
    make_sure_dir_is_empty(path)
    vim.command("Pad ls")
    if path is None:
        vim.command("redraw!")
示例#9
0
def display(query, archive):  # {{{1
    """ Shows a list of notes.

    query: a string representing a regex search. Can be "".

    Builds a list of files for query and then processes it to show the list in the pad format.
    """
    if get_save_dir() == "":
        vim.command('let tmp = confirm("IMPORTANT:\n'\
                'Please set g:pad#dir to a valid path in your vimrc.", "OK", 1, "Error")')
        return
    pad_files = get_filelist(query, archive)
    if len(pad_files) > 0:
        if vim.eval("bufexists('__pad__')") == "1":
            vim.command("bw __pad__")
        if vim.eval('g:pad#position["list"]') == "right":
            vim.command("silent! rightbelow " +
                        str(vim.eval('g:pad#window_width')) + "vnew __pad__")
        elif vim.eval('g:pad#position["list"]') == "full":
            vim.command("silent! new __pad__ | only")
        else:
            vim.command("silent! botright " +
                        str(vim.eval("g:pad#window_height")) + "new __pad__")
        fill_list(pad_files, query != "")
        if query != "":
            vim.command("let b:pad_query = '" + query + "'")
        vim.command("set filetype=pad")
        vim.command("setlocal nomodifiable")
        vim.command("setlocal statusline=%#PreCondit#\ vim-pad%=%#Comment#" + \
                    "%#Special#q%#Comment#:close\ %#Special#dd%#Comment#:delete\ " + \
                    "%#Special#[-+]a%#Comment#:[un]archive\ %#Special#[-+]f%#Comment#:move\ [from\|to]\ " + \
                    "%#Special#<s-f>%#Comment#:search\ %#Special#<s-s>%#Comment#:sort\ ")
    else:
        print "vim-pad: no pads"
示例#10
0
 def add_natural_timestamp(matchobj):
     id_string = matchobj.group("id")
     mtime = str(
         int(
             getmtime(join(get_save_dir(), matchobj.group("id"))) *
             1000000))
     return id_string + " @ " + natural_timestamp(mtime).ljust(19) + " │"
示例#11
0
def display(query, archive): # {{{1
    """ Shows a list of notes.

    query: a string representing a regex search. Can be "".

    Builds a list of files for query and then processes it to show the list in the pad format.
    """
    if get_save_dir() == "":
        vim.command('let tmp = confirm("IMPORTANT:\n'\
                'Please set g:pad#dir to a valid path in your vimrc.", "OK", 1, "Error")')
        return
    pad_files = get_filelist(query, archive)
    if len(pad_files) > 0:
        if vim.eval("bufexists('__pad__')") == "1":
            vim.command("bw __pad__")
        if vim.eval('g:pad#position["list"]') == "right":
            vim.command("silent! rightbelow " + str(vim.eval('g:pad#window_width')) + "vnew __pad__")
        elif vim.eval('g:pad#position["list"]') == "full":
            vim.command("silent! new __pad__ | only")
        else:
            vim.command("silent! botright " + str(vim.eval("g:pad#window_height")) + "new __pad__")
        fill_list(pad_files, query != "")
        if query != "":
            vim.command("let b:pad_query = '" + query + "'")
        vim.command("set filetype=pad")
        vim.command("setlocal nomodifiable")
        vim.command("setlocal statusline=%#PreCondit#\ vim-pad%=%#Comment#" + \
                    "%#Special#q%#Comment#:close\ %#Special#dd%#Comment#:delete\ " + \
                    "%#Special#[-+]a%#Comment#:[un]archive\ %#Special#[-+]f%#Comment#:move\ [from\|to]\ " + \
                    "%#Special#<s-f>%#Comment#:search\ %#Special#<s-s>%#Comment#:sort\ ")
    else:
        print "vim-pad: no pads"
示例#12
0
def search_pads():  # {{{1
    """ Aks for a query and lists the matching notes.
    """
    if get_save_dir() == "":
        vim.command('let tmp = confirm("IMPORTANT:\n'\
                'Please set g:pad#dir to a valid path in your vimrc.", "OK", 1, "Error")')
        return
    query = vim.eval('input(">>> ")')
    display(query, "")
    vim.command("redraw!")
示例#13
0
def search_pads(): # {{{1
    """ Aks for a query and lists the matching notes.
    """
    if get_save_dir() == "":
        vim.command('let tmp = confirm("IMPORTANT:\n'\
                'Please set g:pad#dir to a valid path in your vimrc.", "OK", 1, "Error")')
        return
    query = vim.eval('input(">>> ")')
    display(query, "")
    vim.command("redraw!")
示例#14
0
def update():
    """ Moves a note to a new location if its contents are modified.

    Called on the BufLeave event for the notes.

    """
    if not bool(int(vim.eval('exists("b:pad_modified")'))):
        return

    modified = bool(int(vim.eval("b:pad_modified")))
    can_rename = bool(int(vim.eval("g:pad#rename_files")))
    if modified and can_rename:
        _id = PadInfo(vim.current.buffer).id
        old_path = expanduser(vim.current.buffer.name)

        # if the file already has an extension
        ext = splitext(old_path)[1]
        if ext != '' and ext != vim.eval("g:pad#default_file_extension"):
            return

        fs = filter(
            isfile,
            glob(
                expanduser(join(dirname(vim.current.buffer.name), _id)) + "*"))
        if old_path not in fs:
            if fs == []:
                new_path = expanduser(join(get_save_dir(), _id))
            else:
                exts = map(lambda i: '0' if i == '' else i[1:],
                           map(lambda i: splitext(i)[1], fs))
                new_path = ".".join([
                    expanduser(join(get_save_dir(), _id)),
                    str(int(max(exts)) + 1)
                ])
            new_path = new_path + vim.eval("g:pad#default_file_extension")
            vim.command("bw")
            move(old_path, new_path)
示例#15
0
def set_vim_globals():
    """ Sets global vim preferences and commands.
    """
    # To update the date when files are modified
    if get_save_dir() == "":
        vim.command(
            'echom "vim-pad: IMPORTANT: please set g:pad#dir to a valid path in your vimrc."'
        )
        vim.command("redraw")
    else:
        vim.command(
            'execute "au! BufEnter" printf("%s*", g:pad#dir) ":let b:pad_modified = 0"'
        )
        vim.command(
            'execute "au! BufWritePre" printf("%s*", g:pad#dir) ":let b:pad_modified = eval(&modified)"'
        )
        vim.command(
            'execute "au! BufLeave" printf("%s*", g:pad#dir) ":call pad#UpdatePad()"'
        )

    # vim-pad pollutes the MRU.vim list quite a lot, if let alone.
    # This should fix that.
    if vim.eval('exists(":MRU")') == "2":
        mru_exclude_files = vim.eval("MRU_Exclude_Files")
        if mru_exclude_files != '':
            tail = "\|" + mru_exclude_files
        else:
            tail = ''
        vim.command("let MRU_Exclude_Files = '^" + join(get_save_dir(), ".*") +
                    tail + "'")

    # we forbid writing backups of the notes
    orig_backupskip = vim.eval("&backupskip")
    vim.command(
        "let &backupskip='" +
        ",".join([orig_backupskip, join(get_save_dir(), "*")]) + "'")
示例#16
0
def new_pad(text=None):  #{{{1
    path = join(get_save_dir(),
                PadInfo([text]).id + vim.eval("g:pad#default_file_extension"))
    with open(path, 'w') as new_note:
        new_note.write(text)
示例#17
0
def new_pad(text=None): #{{{1
    path = join(get_save_dir(), PadInfo([text]).id + vim.eval("g:pad#default_file_extension"))
    with open(path, 'w') as new_note:
        new_note.write(text)
示例#18
0
 def add_natural_timestamp(matchobj):
     id_string = matchobj.group("id")
     mtime = str(int(getmtime(join(get_save_dir(), matchobj.group("id")))*1000000))
     return id_string + " @ " + natural_timestamp(mtime).ljust(19) + " │"
示例#19
0
def open_pad(path=None, first_line="", query=''):  # {{{1
    """Creates or opens a note.

    path: a valid path for a note.

    first_line: a string to insert to a new note, if given.

    query: the previous search, if any.

    """
    # we require self.save_dir_set to be set to a valid path
    if get_save_dir() == "":
        vim.command(
            'echom "vim-pad: IMPORTANT: please set g:pad#dir to a valid path in your vimrc."'
        )
        return

    # if no path is provided, we create one using the current time
    if not path:
        path = join(
            get_save_dir(),
            PadInfo([first_line]).id +
            vim.eval("g:pad#default_file_extension"))
    path = path.replace(" ", "\ ")

    def split_for_pad():
        if vim.eval('g:pad#position["pads"]') == 'right':
            vim.command("silent! rightbelow" +
                        str(vim.eval("g:pad#window_width")) + "vsplit " + path)
        else:
            vim.command("silent! botright" +
                        str(vim.eval("g:pad#window_height")) + "split " + path)

    if bool(int(vim.eval("g:pad#open_in_split"))):
        split_for_pad()
    else:
        awa = int(vim.eval("&autowriteall"))
        if bool(int(vim.eval("&modified"))):
            reply = vim.eval(
                'input("vim-pad: the current file has unsaved changes. do you want to save? [Yn] ", "y")'
            )
            if reply == "y":
                vim.command("set autowriteall")
                vim.command("silent! edit " + path)
                if awa == 0:
                    vim.command("set noautowriteall")
            else:
                vim.command(
                    'echom "vim-pad: will have to open pad in a split"')
                split_for_pad()
            vim.command("redraw!")
        else:
            vim.command("silent! edit " + path)

    # we don't keep the buffer when we hide it
    vim.command("set bufhidden=wipe")

    # set the filetype to our default
    if vim.eval('&filetype') in ('', 'conf'):
        vim.command("set filetype=" + vim.eval("g:pad#default_format"))

    # map the local commands
    if bool(int(vim.eval('has("gui_running")'))):
        vim.command(
            "noremap <silent> <buffer> <localleader><delete> :call pad#DeleteThis()<cr>"
        )
    else:
        vim.command(
            "noremap <silent> <buffer> <localleader>dd :call pad#DeleteThis()<cr>"
        )

    vim.command(
        "noremap <silent> <buffer> <localleader>+m :call pad#AddModeline()<cr>"
    )
    vim.command(
        "noremap <silent> <buffer> <localleader>+f :call pad#MoveToFolder()<cr>"
    )
    vim.command(
        "noremap <silent> <buffer> <localleader>-f :call pad#MoveToSaveDir()<cr>"
    )
    vim.command(
        "noremap <silent> <buffer> <localleader>+a :call pad#Archive()<cr>")
    vim.command(
        "noremap <silent> <buffer> <localleader>-a :call pad#Unarchive()<cr>")

    # insert the text in first_line to the buffer, if provided
    if first_line:
        vim.current.buffer.append(first_line, 0)
        vim.command("normal! j")

    # highlight query and jump to it?
    if query != '':
        if vim.eval('g:pad#highlight_query') == '1':
            vim.command("call matchadd('PadQuery', '\c" + query + "')")
        if vim.eval('g:pad#jumpto_query') == '1':
            vim.command("call search('\c" + query + "')")
示例#20
0
def fill_list(files, queried=False, custom_order=False): # {{{1
    """ Writes the list of notes to the __pad__ buffer.

    files: a list of files to process.

    queried: whether files is the result of a query or not.

    custom_order: whether we should keep the order of the list given (implies queried=True).

    Keeps a cache so we only read the notes when the files have been modified.
    """
    global cached_filenames, cached_timestamps, cached_data

    # we won't want to touch the cache
    if custom_order:
        queried = True

    files = filter(exists, [join(get_save_dir(), f) for f in files])

    timestamps = [getmtime(join(get_save_dir(), f)) for f in files]

    # we will have a new list only on the following cases
    if queried or files != cached_filenames or timestamps != cached_timestamps:
        lines = []
        if not custom_order:
            files = reversed(sorted(files, key=lambda i: getmtime(join(get_save_dir(), i))))
        for pad in files:
            pad_path = join(get_save_dir(), pad)
            if isfile(pad_path):
                pad_path = join(get_save_dir(), pad)
                with open(pad_path) as pad_file:
                    info = PadInfo(pad_file)
                    if info.isEmpty:
                        if bool(int(vim.eval("g:pad#show_dir"))):
                            tail = info.folder + u'\u2e25 '.encode('utf-8') + "[EMPTY]"
                        else:
                            tail = "[EMPTY]"
                    else:
                        if bool(int(vim.eval("g:pad#show_dir"))):
                            tail = info.folder + u'\u2e25 '.encode('utf-8') + u'\u21b2'.encode('utf-8').join((info.summary, info.body))
                        else:
                            tail = u'\u21b2'.encode('utf-8').join((info.summary, info.body))
                    lines.append(pad + " @ " + tail)
            else:
                pass

        # we only update the cache if we are not queried, to preserve the global cache
        if not queried:
            cached_data = lines
            cached_timestamps = timestamps
            cached_filenames = files

    # update natural timestamps
    def add_natural_timestamp(matchobj):
        id_string = matchobj.group("id")
        mtime = str(int(getmtime(join(get_save_dir(), matchobj.group("id")))*1000000))
        return id_string + " @ " + natural_timestamp(mtime).ljust(19) + " │"

    if not queried: # we use the cache
        lines = [re.sub("(?P<id>^.*?) @", add_natural_timestamp, line) for line in cached_data]
    else: # we use the new values in lines
        lines = [re.sub("(?P<id>^.*?) @", add_natural_timestamp, line) for line in lines]

    # we now show the list
    if vim.eval('&modifiable') != '1':
        vim.current.buffer.options['modifiable'] = True
    del vim.current.buffer[:] # clear the buffer
    vim.current.buffer.append(list(lines))
    vim.command("normal! dd")
示例#21
0
def open_pad(path=None, first_line="", query=''):  # {{{1
    """Creates or opens a note.

    path: a valid path for a note.

    first_line: a string to insert to a new note, if given.

    query: the previous search, if any.

    """
    # we require self.save_dir_set to be set to a valid path
    if get_save_dir() == "":
        vim.command('echom "vim-pad: IMPORTANT: please set g:pad#dir to a valid path in your vimrc."')
        return

    # if no path is provided, we create one using the current time
    if not path:
        path = join(get_save_dir(),
                    PadInfo([first_line]).id + vim.eval("g:pad#default_file_extension"))
    path = path.replace(" ", "\ ")

    def split_for_pad():
        if vim.eval('g:pad#position["pads"]') == 'right':
            vim.command("silent! rightbelow"
                    + str(vim.eval("g:pad#window_width")) + "vsplit " + path)
        else:
            vim.command("silent! botright"
                    + str(vim.eval("g:pad#window_height")) + "split " + path)

    if bool(int(vim.eval("g:pad#open_in_split"))):
        split_for_pad()
    else:
        awa = int(vim.eval("&autowriteall"))
        if bool(int(vim.eval("&modified"))):
            reply = vim.eval('input("vim-pad: the current file has unsaved changes. do you want to save? [Yn] ", "y")')
            if reply == "y":
                vim.command("set autowriteall")
                vim.command("silent! edit " + path)
                if awa == 0:
                    vim.command("set noautowriteall")
            else:
                vim.command('echom "vim-pad: will have to open pad in a split"')
                split_for_pad()
            vim.command("redraw!")
        else:
            vim.command("silent! edit " + path)

    # we don't keep the buffer when we hide it
    vim.command("set bufhidden=wipe")

    # set the filetype to our default
    if vim.eval('&filetype') in ('', 'conf'):
        vim.command("set filetype=" + vim.eval("g:pad#default_format"))

    # map the local commands
    if bool(int(vim.eval('has("gui_running")'))):
        vim.command("noremap <silent> <buffer> <localleader><delete> :call pad#DeleteThis()<cr>")
    else:
        vim.command("noremap <silent> <buffer> <localleader>dd :call pad#DeleteThis()<cr>")

    vim.command("noremap <silent> <buffer> <localleader>+m :call pad#AddModeline()<cr>")
    vim.command("noremap <silent> <buffer> <localleader>+f :call pad#MoveToFolder()<cr>")
    vim.command("noremap <silent> <buffer> <localleader>-f :call pad#MoveToSaveDir()<cr>")
    vim.command("noremap <silent> <buffer> <localleader>+a :call pad#Archive()<cr>")
    vim.command("noremap <silent> <buffer> <localleader>-a :call pad#Unarchive()<cr>")

    # insert the text in first_line to the buffer, if provided
    if first_line:
        vim.current.buffer.append(first_line, 0)
        vim.command("normal! j")

    # highlight query and jump to it?
    if query != '':
        if vim.eval('g:pad#highlight_query') == '1':
            vim.command("call matchadd('PadQuery', '\c"+query+"')")
        if vim.eval('g:pad#jumpto_query') == '1':
            vim.command("call search('\c"+query+"')")
示例#22
0
def fill_list(files, queried=False, custom_order=False):  # {{{1
    """ Writes the list of notes to the __pad__ buffer.

    files: a list of files to process.

    queried: whether files is the result of a query or not.

    custom_order: whether we should keep the order of the list given (implies queried=True).

    Keeps a cache so we only read the notes when the files have been modified.
    """
    global cached_filenames, cached_timestamps, cached_data

    # we won't want to touch the cache
    if custom_order:
        queried = True

    files = filter(exists, [join(get_save_dir(), f) for f in files])

    timestamps = [getmtime(join(get_save_dir(), f)) for f in files]

    # we will have a new list only on the following cases
    if queried or files != cached_filenames or timestamps != cached_timestamps:
        lines = []
        if not custom_order:
            files = reversed(
                sorted(files, key=lambda i: getmtime(join(get_save_dir(), i))))
        for pad in files:
            pad_path = join(get_save_dir(), pad)
            if isfile(pad_path):
                pad_path = join(get_save_dir(), pad)
                with open(pad_path) as pad_file:
                    info = PadInfo(pad_file)
                    if info.isEmpty:
                        if bool(int(vim.eval("g:pad#show_dir"))):
                            tail = info.folder + u'\u2e25 '.encode(
                                'utf-8') + "[EMPTY]"
                        else:
                            tail = "[EMPTY]"
                    else:
                        if bool(int(vim.eval("g:pad#show_dir"))):
                            tail = info.folder + u'\u2e25 '.encode(
                                'utf-8') + u'\u21b2'.encode('utf-8').join(
                                    (info.summary, info.body))
                        else:
                            tail = u'\u21b2'.encode('utf-8').join(
                                (info.summary, info.body))
                    lines.append(pad + " @ " + tail)
            else:
                pass

        # we only update the cache if we are not queried, to preserve the global cache
        if not queried:
            cached_data = lines
            cached_timestamps = timestamps
            cached_filenames = files

    # update natural timestamps
    def add_natural_timestamp(matchobj):
        id_string = matchobj.group("id")
        mtime = str(
            int(
                getmtime(join(get_save_dir(), matchobj.group("id"))) *
                1000000))
        return id_string + " @ " + natural_timestamp(mtime).ljust(19) + " │"

    if not queried:  # we use the cache
        lines = [
            re.sub("(?P<id>^.*?) @", add_natural_timestamp, line)
            for line in cached_data
        ]
    else:  # we use the new values in lines
        lines = [
            re.sub("(?P<id>^.*?) @", add_natural_timestamp, line)
            for line in lines
        ]

    # we now show the list
    if vim.eval('&modifiable') != '1':
        vim.current.buffer.options['modifiable'] = True
    del vim.current.buffer[:]  # clear the buffer
    vim.current.buffer.append(list(lines))
    vim.command("normal! dd")
示例#23
0
文件: pad.py 项目: amuelli/vim-pad
    def __init__(self, source):
        """

        source can be:

        * a vim buffer
        * a file object
        * a list of strings, one per line
        """

        nchars = int(vim.eval("g:pad#read_nchars_from_files"))
        self.summary = ""
        self.body = ""
        self.isEmpty = True
        self.folder = ""
        self.id = timestamp()

        if source is vim.current.buffer:
            source = source[:10]
        elif source.__class__ == file:
            save_dir = get_save_dir()
            if abspath(source.name).startswith(save_dir):
                pos = len(get_save_dir()), len(basename(source.name))
                self.folder = abspath(source.name)[pos[0]:-pos[1]]
            else:
                self.folder = dirname(relpath(source.name, vim.eval('getcwd()')))
            if vim.eval("g:pad#title_first_line") == '1':
                source = source.readline().split("\n")
            else:
                source = source.read(nchars).split('\n')

        data = [line.strip() for line in source if line != ""]

        if data != []:
            # we discard modelines
            if re.match("^.* vim: set .*:.*$", data[0]):
                data = data[1:]

            self.summary = data[0].strip()
            # vim-orgmode adds tags after whitespace
            org_tags_data = re.search("\s+(?P<tags>:.*$)", self.summary)
            if org_tags_data:
                self.summary = re.sub("\s+:.*$", "", self.summary)
            if self.summary[0] in ("%", "#"):  # pandoc and markdown titles
                self.summary = str(self.summary[1:]).strip()

            self.body = u'\u21b2'.encode('utf-8').join(data[1:]).strip()
            # if we have orgmode tag data, add it to the body
            if org_tags_data:
                self.body = ' '.join(\
                    [" ".join(\
                              map(lambda a: "@" + a, \
                                  filter(lambda a: a != "", \
                                         org_tags_data.group("tags").split(":")))), \
                     self.body])
            # remove extra spaces in bodies
            self.body = re.sub("\s{2,}", "", self.body)

        if self.summary != "":
            self.isEmpty = False
            self.id = self.summary.lower().replace(" ", "_")
            # remove ilegal characters from names (using rules for windows
            # systems to err on the side of precaution)
            self.id = re.sub("[*:<>/\|^]", "", self.id)

        if self.id.startswith("."):
            self.id = re.sub("^\.*", "", self.id)
示例#24
0
def get_selected_path():  # {{{1
    return join(get_save_dir(), vim.current.line.split(" @")[0])
示例#25
0
    def __init__(self, source):
        """

        source can be:

        * a vim buffer
        * a file object
        * a list of strings, one per line
        """

        nchars = int(vim.eval("g:pad#read_nchars_from_files"))
        self.summary = ""
        self.body = ""
        self.isEmpty = True
        self.folder = ""
        self.id = timestamp()

        if source is vim.current.buffer:
            source = source[:10]
        elif source.__class__ == file:
            save_dir = get_save_dir()
            if abspath(source.name).startswith(save_dir):
                pos = len(get_save_dir()), len(basename(source.name))
                self.folder = abspath(source.name)[pos[0]:-pos[1]]
            else:
                self.folder = dirname(
                    relpath(source.name, vim.eval('getcwd()')))
            if vim.eval("g:pad#title_first_line") == '1':
                source = source.readline().split("\n")
            else:
                source = source.read(nchars).split('\n')

        data = [line.strip() for line in source if line != ""]

        if data != []:
            # we discard modelines
            if re.match("^.* vim: set .*:.*$", data[0]):
                data = data[1:]

            self.summary = data[0].strip()
            # vim-orgmode adds tags after whitespace
            org_tags_data = re.search("\s+(?P<tags>:.*$)", self.summary)
            if org_tags_data:
                self.summary = re.sub("\s+:.*$", "", self.summary)
            if self.summary[0] in ("%", "#"):  # pandoc and markdown titles
                self.summary = str(self.summary[1:]).strip()

            self.body = u'\u21b2'.encode('utf-8').join(data[1:]).strip()
            # if we have orgmode tag data, add it to the body
            if org_tags_data:
                self.body = ' '.join(\
                    [" ".join(\
                              map(lambda a: "@" + a, \
                                  filter(lambda a: a != "", \
                                         org_tags_data.group("tags").split(":")))), \
                     self.body])
            # remove extra spaces in bodies
            self.body = re.sub("\s{2,}", "", self.body)

        if self.summary != "":
            self.isEmpty = False
            self.id = self.summary.lower().replace(" ", "_")
            # remove ilegal characters from names (using rules for windows
            # systems to err on the side of precaution)
            self.id = re.sub("[*:<>/\|^]", "", self.id)

        if self.id.startswith("."):
            self.id = re.sub("^\.*", "", self.id)
示例#26
0
def get_selected_path():  # {{{1
    return join(get_save_dir(), vim.current.line.split(" @")[0])