notes

package module
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2020 License: MIT Imports: 22 Imported by: 2

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

Table of Contents

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

Before starting to use, you can try it with examples.

$ git clone https://github.com/rhysd/notes-cli.git
$ cd notes-cli/
$ export NOTES_CLI_HOME="$(pwd)/example/notes-cli"
$ export NOTES_CLI_EDITOR=vim # Set your favorite editor
$ notes list --full
$ notes new test my-local-trial
$ git status # Check what file was created in home

To uninstall:

$ rm -rf "$(notes config home)" # Remove all notes
$ rm "$(which notes)" # Remove an executable

Basic Usage

notes provides some subcommands to manage your markdown notes.

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

Directories structure under notes-cli home is something like:

<HOME>
├── category1
│   ├── nested-category
│   │   └── note3.md
│   ├── note1.md
│   └── note2.md
├── category2
│   ├── note4.md
│   └── note5.md
└── category3
    └── note6.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.

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

Usage

This section describes detailed usages for each operation.

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. The home directory is automatically created.

Category is blog. Every note must belong to one category. Category can be nested with /. For example, if have multiple blogs Blog A and Blog B, you may want to categorize blog posts with categories like blog/A, blog/B.

Tags are golang and file. Tags are labels to organize notes and to make search notes easier. Tags can be omitted.

Category and file name cannot start with . not to make hidden files/directories.

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. (If it is not set, $EDITOR is also referred.)

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.

Flexibly open notes you created

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, --edit (or -e) is a quickest way.

$ notes list --edit
$ 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 in descending order. 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 (up to 10 lines)

with colors.

When output is larger and whole output cannot be shown in screen at once, list does paging for the output using less command (if available). This behavior can be customized by $NOTES_CLI_PAGER.

When there are many notes, it outputs many lines. In the case, a pager tool like less is useful You can also use less with pipe explicitly 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 golang,file How to handle files in Go
  • 1st field indicates a relative path of note file from home directory with different colors. The first part of the path is the category in green, and the second part is the file name in yellow.
  • 2nd field indicates comma-separated tags of the note. When note has no tag, it leaves as blank.
  • 3rd field is the title of note

This is useful for checking many notes at a glance. When output is larger, less is used for paging the output if available.

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

Note Templates

You can create a template of note at each category directory or at root. When .template.md file is put in a category directory or home, it is automatically inserted on notes new.

For example, when HOME/minutes/.template.md is created with following content:

---

- Agenda: 
- Attendee: 


Executing notes new minutes weekly-meeting-2018-11-07 will create a new note with inserting the template like:

weekly-meeting-2018-11-07
=========================
- Category: minutes
- Tags:
- Created: 2018-11-07T14:19:27+09:00

---

- Agenda: 
- Attendee: 

Template file at category directory is prioritized. For example, when notes new minutes weekly-meeting-2018-11-07 is run in following situation,

HOME
├── .template.md
└── minutes
    └── .template.md

HOME/minutes/.template.md is used rather than HOME/.template.md.

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 directory 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.

Configure behavior with environment variables

As described above, some behavior can be configurable with environment variables. Here is a table of all environment variables affecting behavior of notes. Variables starting with $NOTES_ are dedicated for notes command. Others are general environment variables affecting notes behavior. When you want to disable integration of Git, an editor or a pager, please set empty string to the corresponding environment variable like export NOTES_CLI_PAGER=.

Name Default Description
$NOTES_CLI_HOME notes-cli under XDG data dir Home directory of notes. All notes are stored in sub directories
$NOTES_CLI_EDITOR None Your favorite editor command. It can contain options like "vim -g"
$NOTES_CLI_GIT "git" Git command path. It is used for saving notes as Git repository
$NOTES_CLI_PAGER "less -R -F -X" Pager command for paging long output from notes list
$XDG_DATA_HOME None When $NOTES_CLI_HOME is not set, it is used for home
$APPLOCALDATA None Even if $XDG_DATA_HOME is not set, it is used for home on Windows
$EDITOR None When $NOTES_CLI_EDITOR is not set, it is referred to pick editor command
$PAGER None When $NOTES_CLI_PAGER is not set, it is referred to pick pager command

You can see the configurations by notes config command.

Extend notes command by adding new subcommands

Yes. Like Git, notes command tries to run external subcommands when user specifies unknown subcommand. For example, when entering notes foo, notes command notices that it is not a built-in subcommand. Then it attempts to execute notes-foo with the same arguments.

Following arguments are passed to underlying external subcommand:

{full path to notes} {global options...} {subcommand} {local options...}

For example, let's say following script is put in your $PATH as notes-hello.

#!/bin/sh
echo "Hello! $*"

And hit notes hello. It outputs Hello! /path/to/bin/notes hello since given argument hello is simply passed to executed underlying subcommand with full path of notes. So, when hit notes --no-color hello --foo, it outputs Hello! /path/to/bin/notes --no-color hello --foo. By forwarding all arguments, subcommand can refer global options specified before subcommand.

This external subcommand support is useful when you want to extend notes functionality to fit your usage. For example:

  • You can create your own command to upload your blog notes to your blog services.
  • You can create your own alias command like ls -o -s modified -> lsmod.
Shell Completions
  • For zsh:

Please put _notes completion script to your completion directory.

$ git clone https://github.com/rhysd/notes-cli.git
$ cp nodes-cli/completions/zsh/_notes /path/to/completion/dir/

The completion directory must be listed in $fpath.

fpath=(/path/to/completion/dir $fpath)
  • For bash:

Please add following line to your .bashrc.

$ eval "$(notes --completion-script-bash)"
  • For fish:

Please add the completion script under completions/fish/ to your completions directory.

$ git clone https://github.com/rhysd/notes-cli.git
$ cp nodes-cli/completions/fish/notes.fish ~/.config/fish/completions/
Setup man manual

notes command can generate man manual file.

$ notes --help-man > /usr/local/share/man/man1/notes.1
Update itself

notes has the ability to update the executable by itself.

$ notes selfupdate

Before updating, you can only check if the latest version is available by --dry option.

Use from Go program

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

FAQ

Can I 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.

I don't want to show the metadata in note. Can I hide them?

Metadata can be commented out as follows:

some title
==========
<!--
- Category: cat
- Tags:
- Created: 2018-11-09T02:14:27+09:00
-->

Body

The closing comment --> is not included in note body. Commented metadata are not rendered and read only by notes command.

Can I hide metadata by default?

Yes. When .template.md starts with --> (closing comment), notes automatically consider that you expect to hide metadata and insert <!-- proper position.

For example, if you have category1/.template.md,

-->

notes new will create a new note as follows:

some-title
==========
<!--
- Category: category1
- Tags:
- Created: 2018-11-15T23:14:27+09:00
-->

How image resources are managed?

I recommend to create a directory for resources under home.

All non-markdown resources (are ignored by notes command. So you can freely put your .png or .jpg files in the same directory as note markdown files.

Or you can use a separate directory dedicated for images like HOME/images/ or HOME/category1/images. This option may be better than mixing many pictures and note files in the same directory when you use grep.

If you want to differentiate images directory from other category directories, please give . prefix like HOME/.images since category directories cannot have . prefix as their names.

Is it possible to use --color-always by default?

Please use shell's alias feature as follows:

alias notes='notes --color-always'
How can I migrate from memolist.vim?

Please try migration script.

$ git clone https://github.com/rhysd/notes-cli.git
$ cd ./notes-cli
$ ruby ./scripts/migrate-from-memolist.rb /path/to/memolist/dir /path/to/note-cli/home
How can I integrate with Vim?

You can try Vim plugin for notes-cli

If you feel the plugin is too much, you can also try following configuration. Please write following code in your .vimrc.

function! s:notes_grep(args) abort
    let idx = match(a:args, '\s\+\ze/[^/]\+/')
    if idx <= 0
        " When :NotesGrep /pat/
        let paths = join(split(system('notes list'), '\n'), ' ')
        execute 'vimgrep' a:args paths
        return
    endif

    " When :NotesGrep {args} /pat/
    let paths = join(split(system('notes list ' . a:args[:idx]), '\n'), ' ')
    if paths ==# ''
        echohl ErrorMsg | echo 'No file found' | echohl None
        return
    endif
    let pat = a:args[idx:]
    execute 'vimgrep' pat paths
endfunction
command! -nargs=+ NotesGrep call <SID>notes_grep(<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>)
  • :NotesGrep [args] /pat/: It searches notes by :vimgrep with given /pat/. Thanks to :vimgrep, the search result is stored to a quickfix list. You can easily check matches and open the file from the list by open quickfix window with :copen.
  • :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, err := notes.NewConfig()
if err != nil {
	panic(err)
}

// 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

Example
color.NoColor = true

cwd, err := os.Getwd()
if err != nil {
	panic(err)
}

cfg := &notes.Config{
	HomePath: filepath.Join(cwd, "example", "notes-cli"),
}

cmd := notes.ListCmd{
	Config:  cfg,
	Oneline: true,
	Out:     os.Stdout,
}

// Shows oneline notes (relative file path, category, tags, title)
if err := cmd.Do(); err != nil {
	panic(err)
}
Output:

blog/daily/dialy-2018-11-20.md                         dialy-2018-11-20
blog/daily/dialy-2018-11-18.md             notes       dialy-2018-11-18
memo/tasks.md                                          My tasks
memo/notes-urls.md                         notes       URLs for notes
blog/tech/introduction-to-notes-command.md notes       introduction-to-notes-command
blog/tech/how-to-handle-files.md           golang,file How to hanle files in Go

Index

Examples

Constants

This section is empty.

Variables

View Source
var Version = "1.6.2"

Version is version string of notes command. It conforms semantic versioning

Functions

This section is empty.

Types

type Categories added in v1.4.0

type Categories map[string]*Category

Categories is a map from category name to Category instance

func CollectCategories added in v1.4.0

func CollectCategories(cfg *Config, mode CategoryCollectMode) (Categories, error)

CollectCategories collects all categories under home by default. The behavior of collecting categories can be customized with mode parameter. Default mode value is 0 (nothing specified).

func (Categories) Names added in v1.4.0

func (cats Categories) Names() []string

Names returns all category names as slice

func (Categories) Notes added in v1.4.0

func (cats Categories) Notes(cfg *Config) ([]*Note, error)

Notes returns all Note instances which belong to the categories

type CategoriesCmd

type CategoriesCmd struct {
	Config *Config
	// Out is a writer to write output of this command. Kind of stdout is expected
	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 Category added in v1.4.0

type Category struct {
	// Path is a path to the category directory
	Path string
	// Name is a name of category
	Name string
	// NotePaths are paths to notes of the category
	NotePaths []string
}

Category represents a category directory which contains some notes

func (*Category) Notes added in v1.4.0

func (cat *Category) Notes(c *Config) ([]*Note, error)

Notes returns all Note instances which belong to the category

type CategoryCollectMode added in v1.6.0

type CategoryCollectMode uint

CategoryCollectMode customizes the behavior of how to collect categories

const (
	// OnlyFirstCategory is a flag to stop collecting categories earlier. If this flag is included
	// in mode parameter of CollectCategories(), it collects only first category and only first
	// note and stops finding anymore.
	OnlyFirstCategory CategoryCollectMode = 1 << iota
)

type Cmd

type Cmd interface {
	Do() error
}

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
	// EditorCmd is a command of your favorite editor. If $NOTES_CLI_EDITOR is set, it is used. This value is
	// similar to $EDITOR environment variable and can contain command arguments like "vim -g". Otherwise,
	// this value will be empty. When empty, some functionality which requires an editor to open note doesn't
	// work
	EditorCmd string
	// PagerCmd is a command for paging output from 'list' subcommand. If $NOTES_CLI_PAGER is set, it is used.
	PagerCmd string
}

Config represents user configuration of notes command

func NewConfig

func NewConfig() (*Config, error)

NewConfig creates a new Config instance by looking the user's environment. GitPath and EditorPath may be empty when proper configuration is not found. When home directory path cannot be located, this function returns an error

type ConfigCmd

type ConfigCmd struct {
	Config *Config
	// Name is a name of configuration. Must be one of "", "home", "git" or "editor"
	Name string
	// Out is a writer to write output of this command. Kind of stdout is expected
	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 ExternalCmd added in v1.4.0

type ExternalCmd struct {
	// ExePath is a path to executable of the external subcommand
	ExePath string
	// Args is arguments passed to external subcommand. Arguments specified to `notes` are forwarded
	Args []string
	// NotesPath is an executable path of the `notes` command. This is passed to the first argument of external subcommand
	NotesPath string
}

ExternalCmd represents user-defined subcommand

func NewExternalCmd added in v1.4.0

func NewExternalCmd(fromErr error, args []string) (*ExternalCmd, bool)

NewExternalCmd creates ExternalCmd instance from given error and arguments. The error must be parse error of kingpin.Parse(). When the missing subcommand is not detected in the error message, this function returns false as 2nd return value

func (*ExternalCmd) Do added in v1.4.0

func (cmd *ExternalCmd) Do() error

Do invokes external subcommand with exec. If it did not exit successfully this function returns an error

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 is a flag equivalent to --full
	Full bool
	// Category is a regex string equivalent to --cateogry
	Category string
	// Tag is a regex string equivalent to --tag
	Tag string
	// Relative is a flag equivalent to --relative
	Relative bool
	// Oneline is a flag equivalent to --oneline
	Oneline bool
	// Tag is a string indicating how to sort the list. This value is equivalent to --sort option
	SortBy string
	// Edit is a flag equivalent to --edit
	Edit bool
	// Out is a writer to write output of this command. Kind of stdout is expected
	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 MismatchCategoryError added in v1.6.1

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

MismatchCategoryError represents an error caused when a user specifies mismatched category

func (*MismatchCategoryError) Error added in v1.6.1

func (e *MismatchCategoryError) Error() string

func (*MismatchCategoryError) Is added in v1.6.1

func (e *MismatchCategoryError) Is(target error) bool

Is returns if given error is a MismatchCategoryError or not

type NewCmd

type NewCmd struct {
	Config *Config
	// Category is a category name of the new note. This must be a name allowed for directory name
	Category string
	// Filename is a file name of the new note
	Filename string
	// Tags is a comma-separated string of tags of the new note
	Tags string
	// NoInline is a flag equivalent to --no-inline-input
	NoInline bool
	// NoEdit is a flag equivalent to --no-edit
	NoEdit 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. This function will fail when the file is already existing.

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) ReadBodyLines added in v1.5.0

func (note *Note) ReadBodyLines(maxLines int) (string, int, error)

ReadBodyLines reads body of note until maxLines lines and returns it as string and number of lines as int

func (*Note) RelFilePath

func (note *Note) RelFilePath() string

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

func (*Note) TemplatePath added in v1.4.0

func (note *Note) TemplatePath() (string, bool)

TemplatePath resolves a path to template file of the note. If no template is found, it returns false as second return value

type PagerWriter added in v1.5.0

type PagerWriter struct {

	// Cmdline is a string of command line which was spawned
	Cmdline string
	// Err is an error instance which occurred while paging.
	Err error
	// contains filtered or unexported fields
}

PagerWriter is a wrapper of pager command to paging output to writer with pager command such as `less` or `more`. Starting process, writing input to process, waiting process finishes may cause an error. If one of them causes an error, later operations won't be performed. Instead, the prior error is returned.

func StartPagerWriter added in v1.5.0

func StartPagerWriter(pagerCmd string, stdout io.Writer) (*PagerWriter, error)

StartPagerWriter creates a new PagerWriter instance and spawns underlying pager process with given command. pagerCmd can contain options like "less -R". When the command cannot be parsed as shell arguments or starting underlying pager process fails, this function returns an error

func (*PagerWriter) Wait added in v1.5.0

func (pager *PagerWriter) Wait() error

Wait waits until underlying pager process finishes

func (*PagerWriter) Write added in v1.5.0

func (pager *PagerWriter) Write(p []byte) (int, error)

Write writes given payload to underlying pager process's stdin

type SaveCmd

type SaveCmd struct {
	Config *Config
	// Message is a message of Git commit which will be created to save notes. If this value is empty,
	// automatically generated message will be used.
	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 is a flag equivalent to --dry
	Dry bool
	// Slug is a "user/repo" string where releases are put. This field is useful when you forked
	// notes-cli into your own repository.
	Slug string
	// Out is a writer to write output of this command. Kind of stdout is expected
	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 is a category name of tags. If this value is empty, tags of all categories will be output
	Category string
	// Out is a writer to write output of this command. Kind of stdout is expected
	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

Jump to

Keyboard shortcuts

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