notes

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2018 License: MIT Imports: 20 Imported by: 5

README

A small CLI note taking tool with your favorite editor

Linux/Mac Build Status Windows Build Status Coverage Report Documentation

This is a small CLI tool for note taking in terminal with your favorite editor. You can manage (create/open/list) notes via this tool on terminal. This tool also optionally can save your notes thanks to Git to avoid losing your notes.

This tool is intended to be used nicely with other commands such as grep (or ag, rg), rm, filtering tools such as fzf or peco and editors which can be started from command line.

demo screencast

Installation

Download an archive for your OS from release page. It contains an executable. Please unzip the archive and put the executable in a directory in $PATH.

Or you can install by building from source directly as follows. Go toolchain is necessary.

$ go get -u github.com/rhysd/notes-cli/cmd/notes

Usage

Basic Usage

notes provides some subcommands to manage your markdown notes.

  • Create a new note with notes new <category> <filename> [<tags>].
  • Open existing note by notes ls -e and your favorite editor. $NOTES_CLI_EDITOR must be set.
  • Check existing notes on terminal with notes ls -o (-o means showing one line information for each note).

By notes list (omitting -o), it shows paths separated by newline. By choosing one line from the output and pass it to your editor's command as argument, you can easily open the note in your editor.

Every note must have one category. And it can have zero or more tags.

Create a new note

For example,

$ notes new blog how-to-handle-files golang,file

creates a note file at <HOME>/notes-cli/blog/how-to-handle-files.md where <HOME> is XDG Data directory (on macOS, ~/.local/share/notes-cli) by default and can be specified by $NOTES_CLI_HOME environment variable. The home directory is automatically created.

Category is blog. Every note must belong to one category.

Tags are golang and file. Tags can be omitted.

Directories structure under home is something like:

<HOME>
├── category1
│   ├── note1.md
│   ├── note2.md
│   └── note3.md
├── category2
│   ├── note4.md
│   └── note5.md
└── category3
    └── note6.md

You can see more practical example home directory at example directory.

If you set your favorite editor to $NOTES_CLI_EDITOR environment variable, it opens the newly created note file with it. You can seamlessly edit the file.

how-to-handle-files
===================
- Category: blog
- Tags: golang, file
- Created: 2018-10-28T07:19:27+09:00

Please do not remove - Category: ..., - Tags: ... and - Created: ... lines and title. They are used by notes command (modifying them is OK). Default title is file name. You can edit the title and body of note as follows:

How to handle files in Go
=========================
- Category: blog
- Tags: golang, file
- Created: 2018-10-28T07:19:27+09:00

Please read documentation.
GoDoc explains everything.

Note that every note is under the category directory of the note. When you change a category of note, you also need to adjust directory structure manually (move the note file to new category directory).

For more details, please check notes new --help.

Open notes you created flexibly

Let's say to open some notes you created.

You can show the list of note paths with:

$ notes list # or `notes ls`

For example, now there is only one note so it shows one path

/Users/me/.local/share/notes-cli/blog/how-to-handle-files.md

Note that /Users/<NAME>/.local/share is a default XDG data directory on macOS or Linux and you can change it by setting $NOTES_CLI_HOME environment variable.

To open the listed notes with your editor, --editor (or -e) is a quickest way.

$ notes list --editor
$ notes ls -e

When there are multiple notes, note is output per line. So you can easily retrieve some notes from them by filtering the list with grep, head, peco, fzf, ...

$ notes ls | grep -l file | xargs -o vim

Or following also works.

vim $(notes ls | xargs grep file)

And searching notes is also easy by using grep, rg, ag, ...

$ notes ls | xargs ag documentation

When you want to search and open it with Vim, it's also easy.

$ notes ls | xargs ag -l documentation | xargs -o vim

notes ls accepts --sort option and changes the order of list. By default, the order is created date time of note. By ordering with modified time of note, you can instantly open last-modified note as follows since first line is a path to the note most recently modified.

$ note ls --sort modified | head -1 | xargs -o vim

For more details, please check notes list --help.

Check notes you created as list

notes list also can show brief of notes to terminal.

You can also show the full information of notes on terminal with --full (or -f) option.

$ notes list --full

For example,

/Users/me/.local/share/notes-cli/blog/how-to-handle-files.md
Category: blog
Tags: golang, file
Created: 2018-10-28T07:19:27+09:00

How to handle files in Go
=========================

Please read documentation.
GoDoc explains everything.

It shows

  • Full path to the note file
  • Metadata Category, Tags and Created
  • Title of note
  • Body of note (upto 200 bytes)

with colors.

When there are many notes, it outputs many lines. In the acse, a pager tool like less is useful to see the output per page. -A global option is short of --always-color.

$ notes -A ls --full | less -R

When you want to see the all notes quickly, --oneline (or -o) may be more useful than --full. notes ls --oneline shows one brief of note per line.

For example,

blog/how-to-handle-files.md blog golang,file How to handle files in Go
  • First field indicates a relative path of note file from home directory.
  • Second field indicates a category of the note.
  • Third field indicates comma-separated tags of the note. When note has no tag, it leaves as blank.
  • Rest is a title of the note

This is useful for checking many notes at a glance.

For more details, please see notes list --help.

Save notes to Git repository

Finally you can save your notes as revision of Git repository.

$ notes save

It saves all your notes under your notes-cli diretory as Git repository. It adds all changes in notes and automatically creates commit.

By default, it only adds and commits your notes to the repository. But if you set origin remote to the repository, it automatically pushes the notes to the remote.

For more details, please see notes save --help.

Use from Go program

This command can be used from Go program as a library. Please read API documentation to know the interfaces.

FAQ

I want to specify /path/to/dir as home

Please set it to environment variable.

export NOTES_CLI_HOME=/path/to/dir
How can I grep notes?

Please combine grep tools with notes list on your command line. For example,

$ grep -E some word $(notes list)
$ ag some word $(notes list)

If you want to filter with categories or tags, please use -c and/or -t of list command.

How can I filter notes interactively and open it with my editor?

Please pipe the list of paths from notes list. Following is an example with peco and Vim.

$ notes list | peco | xargs -o vim --not-a-term
Can I open the latest note without selecting it from list?

Output of notes list is sorted by created date time by default. By using head command, you can choose the latest note in the list.

$ vim "$(notes list | head -1)"

If you want to access to the last modified note, sorting by modified and taking first item by head should work.

$ vim "$(notes list --sort modified | head -1)"

By giving --sort (or -s) option to notes list, you can change how to sort. Please see notes list --help for more details.

How can I remove some notes?

Please use rm and notes list. Following is an example that all notes of specific category foo are removed.

$ rm $(notes list -c foo)

Thanks to Git repository, this does not remove your notes completely until you run notes save next time.

Can I nest categories?

Categories cannot be nested. Instead, you can define your own nested naming rule for categories. For example blog-personal-public can indicate blog entries which is personal and publicly posted. Other categories would be named like blog-personal-private, blog-company-public, ... It's up to you.

How can I integrate with Vim?

Please write following code in your .vimrc.

function! s:notes_selection_done(selected) abort
    silent! autocmd! plugin-notes-cli
    let home = substitute(system('notes config home'), '\n$', '', '')
    let sep = has('win32') ? '\' : '/'
    let path = home . sep . split(a:selected, ' ')[0]
    execute 'split' '+setf\ markdown' path
    echom 'Note opened: ' . a:selected
endfunction
function! s:notes_open(args) abort
    execute 'terminal ++close bash -c "notes list --oneline | peco"'
    augroup plugin-notes-cli
        autocmd!
        autocmd BufWinLeave <buffer> call <SID>notes_selection_done(getline(1))
    augroup END
endfunction
command! -nargs=* NotesOpen call <SID>notes_open(<q-args>)

function! s:notes_new(...) abort
    if has_key(a:, 1)
        let cat = a:1
    else
        let cat = input('category?: ')
    endif
    if has_key(a:, 2)
        let name = a:2
    else
        let name = input('filename?: ')
    endif
    let tags = get(a:, 3, '')
    let cmd = printf('notes new --no-inline-input %s %s %s', cat, name, tags)
    let out = system(cmd)
    if v:shell_error
        echohl ErrorMsg | echomsg string(cmd) . ' failed: ' . out | echohl None
        return
    endif
    let path = split(out)[-1]
    execute 'edit!' path
    normal! Go
endfunction
command! -nargs=* NotesNew call <SID>notes_new(<f-args>)

function s:notes_last_mod(args) abort
    let out = system('notes list --sort modified ' . a:args)
    if v:shell_error
        echohl ErrorMsg | echomsg string(cmd) . ' failed: ' . out | echohl None
        return
    endif
    let last = split(out)[0]
    execute 'edit!' last
endfunction
command! -nargs=* NotesLastMod call <SID>notes_last_mod(<q-args>)
  • :NotesOpen [args]: It shows notes as list with incremental filtering thanks to peco command. The chosen note is opened in a new buffer. args is passed to notes list command. So you can easily filter paths by categories (-c) or tags (-t).
  • :NotesNew [args]: It creates a new note and opens it with a new buffer. args is the same as notes new but category and file name can be empty. In the case, Vim ask you to input them after starting the command.
  • :NotesLastMod [args]: It opens the last modified note in new buffer. When args is given, it is passed to underlying notes list command execution so you can filter result by categories and/or tags with -c or -t.

License

MIT License

Documentation

Overview

Package notes is a library which consists notes command.

https://github.com/rhysd/notes-cli/tree/master/cmd/notes

This library is for using notes command programmatically from Go program. It consists structs which represent each subcommands.

1. Create Config instance with NewConfig 2. Create an instance of subcommand you want to run with config 3. Run it with .Do() method. It will return an error if some error occurs

import (
	"bytes"
	"fmt"
	"github.com/rhysd/notes-cli"
	"os"
	"strings"
)

var buf bytes.Buffer

// Create user configuration
cfg := notes.NewConfig()

// Prepare `notes list` command
cmd := &notes.ListCmd{
	Config: cfg,
	Relative: true,
	Out: &buf
}

// Runs the command
if err := cmd.Do(); err != nil {
	fmt.Fprintln(os.Stdout, err)
}

paths := strings.Split(strings.Trim(buf.String(), "\n"), "\n")
fmt.Println("Note paths:", paths)

For usage of `notes` command, please read README of the repository.

https://github.com/rhysd/notes-cli/blob/master/README.md

Index

Constants

This section is empty.

Variables

View Source
var Version = "1.1.0"

Version is version string of notes command

Functions

func WalkNotes

func WalkNotes(cat string, cfg *Config, pred func(path string, note *Note) error) error

WalkNotes walks all notes with given predicate. If given category string is an empty, it traverses notes of all categories. Otherwise, it only traverses notes of the specified categories. When the category does not exist, this function returns an error. When given predicate returns an error or when loading a note fails, this function stops traversing and immediately returns the error

Types

type CategoriesCmd

type CategoriesCmd struct {
	Config *Config
	Out    io.Writer
	// contains filtered or unexported fields
}

CategoriesCmd represents `notes categories` command. Each public fields represent options of the command. Out field represents where this command should output.

func (*CategoriesCmd) Do

func (cmd *CategoriesCmd) Do() error

Do runs `notes categories` command and returns an error if occurs

type Cmd

type Cmd interface {
	Do() error
	// contains filtered or unexported methods
}

Cmd is an interface for subcommands of notes command

func ParseCmd

func ParseCmd(args []string) (Cmd, error)

ParseCmd parses given arguments as command line options and returns corresponding subcommand instance. When no subcommand matches or argus contains invalid argument, it returns an error

type Config

type Config struct {
	// HomePath is a file path to directory of home of notes command. If $NOTES_CLI_HOME is set, it is used.
	// Otherwise, notes-cli directory in XDG data directory is used. This directory is automatically created
	// when config is created
	HomePath string
	// GitPath is a file path to `git` executable. If $NOTES_CLI_GIT is set, it is used.
	// Otherwise, `git` is used by default. This is optional and can be empty. When empty, some command
	// and functionality which require Git don't work
	GitPath string
	// EditorPath is a file path to executable of your favorite editor. If $NOTES_CLI_EDITOR is set, it is used.
	// Otherwise, this value will be empty. When empty, some functionality which requires an editor to open note
	// doesn't work
	EditorPath string
}

Config represents user configuration of notes command

func NewConfig

func NewConfig() (*Config, error)

NewConfig creates a new Config instance with looking the user's environment

type ConfigCmd

type ConfigCmd struct {
	Config *Config
	Name   string
	Out    io.Writer
	// contains filtered or unexported fields
}

ConfigCmd represents `notes config` command. Each public fields represent options of the command. Out field represents where this command should output.

func (*ConfigCmd) Do

func (cmd *ConfigCmd) Do() error

Do runs `notes config` command and returns an error if occurs

type Git

type Git struct {
	// contains filtered or unexported fields
}

Git represents Git command for specific repository

func NewGit

func NewGit(c *Config) *Git

NewGit creates Git instance from Config value. Home directory is assumed to be a root of Git repository

func (*Git) AddAll

func (git *Git) AddAll() error

AddAll runs `git add -A`

func (*Git) Command

func (git *Git) Command(subcmd string, args ...string) *exec.Cmd

Command returns exec.Command instance which runs given Git subcommand with given arguments

func (*Git) Commit

func (git *Git) Commit(msg string) error

Commit runs `git commit` with given message

func (*Git) Exec

func (git *Git) Exec(subcmd string, args ...string) (string, error)

Exec runs runs given Git subcommand with given arguments

func (*Git) Init

func (git *Git) Init() error

Init runs `git init` with no argument

func (*Git) Push

func (git *Git) Push(remote, branch string) error

Push pushes given branch of repository to the given remote

func (*Git) TrackingRemote

func (git *Git) TrackingRemote() (string, string, error)

TrackingRemote returns remote name branch name. It fails when current branch does not track any branch

type ListCmd

type ListCmd struct {
	Config   *Config
	Full     bool
	Category string
	Tag      string
	Relative bool
	Oneline  bool
	SortBy   string
	Edit     bool
	Out      io.Writer
	// contains filtered or unexported fields
}

ListCmd represents `notes list` command. Each public fields represent options of the command Out field represents where this command should output.

func (*ListCmd) Do

func (cmd *ListCmd) Do() error

Do runs `notes list` command and returns an error if occurs

type NewCmd

type NewCmd struct {
	Config   *Config
	Category string
	Filename string
	Tags     string
	NoInline bool
	// contains filtered or unexported fields
}

NewCmd represents `notes new` command. Each public fields represent options of the command

func (*NewCmd) Do

func (cmd *NewCmd) Do() error

Do runs `notes new` command and returns an error if occurs

type Note

type Note struct {
	// Config is a configuration of notes command which was created by NewConfig()
	Config *Config
	// Category is a category string. It must not be empty
	Category string
	// Tags is tags of note. It can be empty and cannot contain comma
	Tags []string
	// Created is a datetime when note was created
	Created time.Time
	// File is a file name of the note
	File string
	// Title is a title string of the note. When the note is not created yet, it may be empty
	Title string
}

Note represents a note stored on filesystem or will be created

func LoadNote

func LoadNote(path string, cfg *Config) (*Note, error)

LoadNote reads note file from given path, parses it and creates Note instance. When given file path does not exist or when the file does note contain mandatory metadata ('Category', 'Tags' and 'Created'), this function returns an error

func NewNote

func NewNote(cat, tags, file, title string, cfg *Config) (*Note, error)

NewNote creates a new note instance with given parameters and configuration. Category and file name cannot be empty. If given file name lacks file extension, it automatically adds ".md" to file name.

func (*Note) Create

func (note *Note) Create() error

Create creates a file of the note. When title is empty, file name omitting file extension is used for it.

func (*Note) DirPath

func (note *Note) DirPath() string

DirPath returns the absolute category directory path of the note

func (*Note) FilePath

func (note *Note) FilePath() string

FilePath returns the absolute file path of the note

func (*Note) Open

func (note *Note) Open() error

Open opens the note using an editor command user set. When user did not set any editor command with $NOTES_CLI_EDITOR, this method fails. Otherwise, an editor process is spawned with argument of path to the note file

func (*Note) ReadBodyN

func (note *Note) ReadBodyN(maxBytes int64) (string, error)

ReadBodyN reads body of note until maxBytes bytes and returns it as string

func (*Note) RelFilePath

func (note *Note) RelFilePath() string

RelFilePath returns the relative file path of the note from home directory

type SaveCmd

type SaveCmd struct {
	Config  *Config
	Message string
	// contains filtered or unexported fields
}

SaveCmd represents `notes save` command. Each public fields represent options of the command

func (*SaveCmd) Do

func (cmd *SaveCmd) Do() error

Do runs `notes save` command and returns an error if occurs

type SelfupdateCmd added in v1.1.0

type SelfupdateCmd struct {
	Dry bool
	Out io.Writer
	// contains filtered or unexported fields
}

SelfupdateCmd represents `notes selfupdate` subcommand.

func (*SelfupdateCmd) Do added in v1.1.0

func (cmd *SelfupdateCmd) Do() error

Do method checks the newer version binary. If new version is available, it updates myself with the latest binary.

type TagsCmd

type TagsCmd struct {
	Config   *Config
	Category string
	Out      io.Writer
	// contains filtered or unexported fields
}

TagsCmd represents `notes tags` command. Each public fields represent options of the command Out field represents where this command should output.

func (*TagsCmd) Do

func (cmd *TagsCmd) Do() error

Do runs `notes tags` command and returns an error if occurs

Directories

Path Synopsis
cmd
notes command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL