Update 2026-01-25 09:38 OpenBSD/amd64-t14

This commit is contained in:
c0dev0id
2026-01-25 09:38:17 +01:00
parent 0769d7a789
commit 186dfa8096
1240 changed files with 189747 additions and 315946 deletions

View File

@@ -0,0 +1,20 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
[*.ledger]
indent_style = space
indent_size = 4
max_line_length = 120
[*.vim]
indent_style = space
indent_size = 2
max_line_length = 120
[*.md]
trim_trailing_whitespace = false

View File

@@ -0,0 +1 @@
github: [alerque]

View File

@@ -0,0 +1,13 @@
name: Reviewdog
on: [pull_request]
jobs:
vint:
name: vint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: vint
uses: reviewdog/action-vint@v1
with:
github_token: ${{ secrets.github_token }}
reporter: github-pr-review

View File

@@ -0,0 +1,42 @@
name: Vader
on: [push, pull_request]
jobs:
vader:
name: vader
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
vimFlavor: ["vim", "nvim"]
ledgerFlavor: ["ledger", "hledger"]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Enable Universe package repository
run: |
sudo add-apt-repository universe
sudo apt-get update
- name: Install ${{ matrix.ledgerFlavor }}
run: |
sudo apt-get install ${{ matrix.ledgerFlavor }}
- name: Install ${{ matrix.vimFlavor }}
run: |
sudo apt-get install ${{ matrix.vimFlavor == 'nvim' && 'neovim' || 'vim' }}
- name: Review versions
run: |
${{ matrix.ledgerFlavor }} --version
${{ matrix.vimFlavor }} --version
- name: Fetch Vader
run: |
git clone --depth 1 https://github.com/junegunn/vader.vim.git
- name: Run test suite
run: |
${{ matrix.vimFlavor == 'nvim' && 'nvim --headless' || 'vim -N' }} \
-u <(cat << VIMRC
filetype off
set rtp+=vader.vim
set rtp+=.
filetype plugin indent on
syntax enable
VIMRC
) "+Vader! spec/*"

View File

@@ -0,0 +1,17 @@
name: Vint
on: [push]
jobs:
vint:
name: vint
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: '3.10'
- name: Setup dependencies
run: pip install vim-vint
- name: Lint Vimscript
run: vint .

View File

@@ -0,0 +1 @@
tags

View File

@@ -0,0 +1,5 @@
cmdargs:
severity: style_problem
color: true
env:
neovim: false

View File

@@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,46 @@
git := which('git')
just := just_executable()
nvim := which('nvim')
vim := which('vim')
set unstable := true
ledger := "ledger"
[default]
[private]
@list:
{{ just }} --list --unsorted
[no-cd]
preview-vim *ARGS: (preview vim + ' --clean' ARGS)
[no-cd]
preview-nvim *ARGS: (preview nvim + ' --clean' ARGS)
[no-cd]
[private]
preview vimcmd *ARGS:
{{ vimcmd }} \
-c 'let g:ledger_bin = "{{ ledger }}"' \
-c {{ quote("let &runtimepath=\"" + justfile_directory() + ",\" . &runtimepath") }} \
-c 'filetype detect' \
{{ ARGS }}
[no-cd]
check-vim *ARGS: (check vim + ' --clean -N' ARGS)
[no-cd]
check-nvim *ARGS: (check nvim + ' --clean --headless' ARGS)
[no-cd]
[private]
check vimcmd *ARGS:
test -d vader.vim || {{ git }} clone --depth 1 https://github.com/junegunn/vader.vim.git
{{ vimcmd }} \
-c 'let g:ledger_bin = "{{ ledger }}"' \
-c {{ quote("let &runtimepath=\"" + justfile_directory() + "/vader.vim," + justfile_directory() + ",\" . &runtimepath") }} \
-c 'filetype detect' \
-c 'source vader.vim/plugin/vader.vim' \
{{ ARGS }} \
'+Vader! spec/*'

View File

@@ -0,0 +1,5 @@
Copyright (C) YEAR by AUTHOR EMAIL
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

View File

@@ -0,0 +1,117 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

View File

@@ -0,0 +1,320 @@
# vim-ledger
[![Vint](https://github.com/ledger/vim-ledger/workflows/Vint/badge.svg)](https://github.com/ledger/vim-ledger/actions?workflow=Vint)
[![Vader](https://github.com/ledger/vim-ledger/workflows/Vader/badge.svg)](https://github.com/ledger/vim-ledger/actions?workflow=Vader)
Filetype detection, syntax highlighting, auto-formatting, auto-completion, and other tools for working with ledger files.
Compatible with both [`ledger`][ledgercli] and [`hledger`][hledger].
See [plaintextaccounting.org][pta] for background information and other useful links.
## Usage
Install as you would any other VIM plugin.
There are a variety of ways depending on your plugin manager.
For example with [Pathogen](https://github.com/tpope/vim-pathogen) you would clone this repository into your configuration directory.
With [vim-plug](https://github.com/junegunn/vim-plug) and many similar ones, you would declare it in your rc file like this, then run `:PlugInstall`:
```vimscript
Plug 'ledger/vim-ledger'
```
### Install using VIM packages functionality (vim 8+)
To install as a single plugin, using VIM packages functionality first create a target folder:
``` plugin
mkdir -p ~/.vim/pack/ledger/start
cd ~/.vim/pack/ledger/start
git clone <URL>
```
Edit .vimrc and append the line:
```
set loadplugins
```
You can also manually copy the corresponding directories into your VIM plugins directory.
One installed this plugin will identify files ending with `.ldg`, `.ledger`, or `.journal` as ledger files automatically.
Alternatively if you use a different extension you can add a modeline to each like this:
```ledger
; vim: filetype=ledger
```
## Tips and useful commands
* Try account-completion (as explained below)
* `:call ledger#transaction_date_set(line('.'), 'auxiliary')`
will set today's date as the auxiliary date of the current transaction.
You can use also `primary` or `unshift` in place of `auxiliary`.
When you pass "unshift" the old primary date will be set as the auxiliary date and today's date will be set as the new primary date.
To use a different date pass a date measured in seconds since 1st Jan 1970 as the third argument.
* `:call ledger#transaction_state_set(line('.'), '*')`
sets the state of the current transaction to '*'.
You can use this in custom mappings.
* `:call ledger#transaction_state_toggle(line('.'), ' *?!')`
will toggle through the provided transaction states.
You can map this to double-clicking for example:
noremap <silent><buffer> <2-LeftMouse>\
:call ledger#transaction_state_toggle(line('.'), ' *?!')<CR>
* Align commodities at the decimal point. See `help ledger-tips`.
* `:call ledger#entry()`
will replace the text on the current line with a new transaction based on the replaced text.
## Configuration
Include the following let-statements somewhere in your `.vimrc` to modify the behaviour of the ledger filetype.
### Ledger / HLedger Configuration
* Path to the `ledger` executable:
let g:ledger_bin = 'ledger'
* Whether to use ledger or hledger specific features.
Setting this value is optional and in most cases will be guessed correctly based on `g:ledger_bin`, but in the event it isn't guessed correctly or you want to use different syntax features even with your default tooling setup for the other engine this flag can be set to override the value.
let g:ledger_is_hledger = v:true
* Additional default options for the `ledger` executable:
let g:ledger_extra_options = ''
* The file to be used to generate reports:
let g:ledger_main = '%:p'
The default is to use the current file.
=== Completion Settings ===
* To use a custom external system command to generate a list of account names for completion, set the following.
If g:ledger_bin is set, this will default to running that command with arguments to parse the current file using the accounts subcommand (works with ledger or hledger), otherwise it will parse the postings in the current file itself.
let g:ledger_accounts_cmd = 'ledger accounts'
* To use a custom external system command to generate a list of descriptions for completion, set the following.
If `g:ledger_bin` is set, this will default to running that command with arguments to parse the current file using the descriptions subcommand (works with ledger or hledger), otherwise it will parse the transactions in the current file itself.
let g:ledger_descriptions_cmd = 'ledger payees'
* If you want account completion based on fuzzy matching instead of the default sub-level completion:
let g:ledger_fuzzy_account_completion = 1
* If you want the account completion to be sorted by level of detail/depth instead of alphabetical:
let g:ledger_detailed_first = 1
* Show only exact matches in completion:
let g:ledger_exact_only = 1
* Include the original text in completion results:
let g:ledger_include_original = 1
* Enable spell checking for account names:
let g:ledger_accounts_spell = 1
### Alignment and Formatting Settings
* Specify at which column decimal separators should be aligned:
let g:ledger_align_at = 60
* Decimal separator for alignment:
let g:ledger_decimal_sep = '.'
* Specify alignment on the first or last matching separator:
let g:ledger_align_last = v:false
* Default commodity used by `ledger#align_amount_at_cursor()`:
let g:ledger_default_commodity = ''
* Align on the commodity location instead of the amount:
let g:ledger_align_commodity = 1
* Flag that tells whether the commodity should be prepended or appended to the amount:
let g:ledger_commodity_before = 1
* String to be put between the commodity and the amount:
let g:ledger_commodity_sep = ''
* Enable spell checking for commodity symbols:
let g:ledger_commodity_spell = 1
### Folding Settings
* Number of columns that will be used to display the foldtext.
Set this when you think that the amount is too far off to the right.
let g:ledger_maxwidth = 80
* String that will be used to fill the space between account name and amount in the foldtext.
Set this to get some kind of lines or visual aid.
let g:ledger_fillstring = ' -'
* By default vim will fold ledger transactions, leaving surrounding blank lines unfolded.
You can use `g:ledger_fold_blanks` to hide blank lines following a transaction.
let g:ledger_fold_blanks = 0
A value of 0 will disable folding of blank lines, 1 will allow folding of a single blank line between transactions; any larger value will enable folding unconditionally.
Note that only lines containing no trailing spaces are considered for folding.
You can take advantage of this to disable this feature on a case-by-case basis.
### Date Format
* Format of transaction date:
let g:ledger_date_format = '%Y/%m/%d'
### Report Window Settings
* Position of a report buffer:
let g:ledger_winpos = 'B'
Use `b` for bottom, `t` for top, `l` for left, `r` for right.
Use uppercase letters if you want the window to always occupy the full width or height.
### Quickfix Window Settings
* Flag that tells whether a location list or a quickfix list should be used:
let g:ledger_use_location_list = 0
The default is to use the quickfix window.
Set to 1 to use a location list.
* Position of the quickfix/location list:
let g:ledger_qf_vertical = 0
Set to 1 to open the quickfix window in a vertical split.
* Size of the quickfix window:
let g:ledger_qf_size = 10
This is the number of lines of a horizontal quickfix window, or the number of columns of a vertical quickfix window.
* Flag to show or hide filenames in the quickfix window:
let g:ledger_qf_hide_file = 1
Filenames in the quickfix window are hidden by default.
Set this to 0 if you want filenames to be visible.
* Format of quickfix register reports (see `:Register`):
let g:ledger_qf_register_format =
\ '%(date) %(justify(payee, 50)) '.
\ '%(justify(account, 30)) %(justify(amount, 15, -1, true)) '.
\ '%(justify(total, 15, -1, true))\n'
The format is specified using the standard Ledger syntax for `--format`.
* Format of the reconcile quickfix window (see `:Reconcile`):
let g:ledger_qf_reconcile_format =
\ '%(date) %(justify(code, 4)) '.
\ '%(justify(payee, 50)) %(justify(account, 30)) '.
\ '%(justify(amount, 15, -1, true))\n'
The format is specified using the standard Ledger syntax for `--format`.
### Balance Display Settings
* Text of the output of the `:Balance` command:
let g:ledger_cleared_string = 'Cleared: '
let g:ledger_pending_string = 'Cleared or pending: '
let g:ledger_target_string = 'Difference from target: '
### Advanced Settings
* Disable automatic detection of ledger binary:
let g:ledger_no_bin = 1
* Enable automatic formatting with the ledger binary (potentially dangerous):
let g:ledger_dangerous_formatprg = 1
WARNING: This feature can cause data loss when run on non-transaction blocks.
## Completion
Omni completion is implemented for transactions descriptions and posting account names.
### Accounts
By default, account names are matched by the start of every sub-level.
When you insert an account name like this:
Asse<C-X><C-O>
You will get a list of top-level accounts that start like this.
Go ahead and try something like:
As:Ban:Che<C-X><C-O>
When you have an account like this, 'Assets:Bank:Checking' should show up.
If fuzzy matching based account completion is enabled, the matches are
loaded based on string similarity and without regard for the sub-levels.
In the previous example, with fuzzy matching enabled, you could load up
matches by doing something like:
Chec<C-X><C-O>
Notice that we did not need to write the initial account components.
When you want to complete on a virtual transaction, it's currently best to keep the cursor in front of the closing bracket.
Of course you can insert the closing bracket after calling the completion, too.
## License
Copyright 20192025 Caleb Maclennan
Copyright 20092017 Johann Klähn
Copyright 2009 Stefan Karrmann
Copyright 2005 Wolfgang Oertl
This program is free software:
you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <https://www.gnu.org/licenses/>.
[hledger]: https://hledger.org/
[ledgercli]: https://www.ledger-cli.org/
[pta]: https://plaintextaccounting.org/

View File

@@ -1,128 +0,0 @@
vim-ledger
==========
This is the ledger filetype for Vim.
Usage
-----
Copy each file to the corresponding directory in your `~/.vim` directory or
install using [Pathogen](https://github.com/tpope/vim-pathogen).
You can also use a modeline like this in every ledger file:
vim:filetype=ledger
Tips and useful commands
------------------------
* Try account-completion (as explained below)
* `:call ledger#transaction_date_set(line('.'), 'auxiliary')`
will set today's date as the auxiliary date of the current transaction. You
can use also `primary` or `unshift` in place of `auxiliary`. When you pass
"unshift" the old primary date will be set as the auxiliary date and today's
date will be set as the new primary date.
To use a different date pass a date measured in seconds since 1st Jan 1970
as the third argument.
* `:call ledger#transaction_state_set(line('.'), '*')`
sets the state of the current transaction to '*'. You can use this in custom
mappings.
* `:call ledger#transaction_state_toggle(line('.'), ' *?!')`
will toggle through the provided transaction states. You can map this to
double-clicking for example:
noremap <silent><buffer> <2-LeftMouse>\
:call ledger#transaction_state_toggle(line('.'), ' *?!')<CR>
* Align commodities at the decimal point. See `help ledger-tips`.
* `:call ledger#entry()`
will replace the text on the current line with a new transaction based
on the replaced text.
Configuration
-------------
Include the following let-statements somewhere in your `.vimrc` to modify the
behaviour of the ledger filetype.
* Number of columns that will be used to display the foldtext. Set this when
you think that the amount is too far off to the right.
let g:ledger_maxwidth = 80
* String that will be used to fill the space between account name and amount in
the foldtext. Set this to get some kind of lines or visual aid.
let g:ledger_fillstring = ' -'
* If you want the account completion to be sorted by level of detail/depth
instead of alphabetical, include the following line:
let g:ledger_detailed_first = 1
* By default vim will fold ledger transactions, leaving surrounding blank lines
unfolded. You can use `g:ledger_fold_blanks` to hide blank lines following a
transaction.
let g:ledger_fold_blanks = 0
A value of 0 will disable folding of blank lines, 1 will allow folding of a
single blank line between transactions; any larger value will enable folding
undconditionally.
Note that only lines containing no trailing spaces are considered for
folding. You can take advantage of this to disable this feature on a
case-by-case basis.
Completion
----------
Omni completion is currently implemented for account names only.
### Accounts
Account names are matched by the start of every sub-level. When you
insert an account name like this:
Asse<C-X><C-O>
You will get a list of top-level accounts that start like this.
Go ahead and try something like:
As:Ban:Che<C-X><C-O>
When you have an account like this, 'Assets:Bank:Checking' should show up.
When you want to complete on a virtual transaction, it's currently best
to keep the cursor in front of the closing bracket. Of course you can
insert the closing bracket after calling the completion, too.
License
-------
Copyright 2019 Caleb Maclennan
Copyright 20092017 Johann Klähn
Copyright 2009 Stefan Karrmann
Copyright 2005 Wolfgang Oertl
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,22 @@
version = 1
[[annotations]]
path = ["*.vim", "doc/ledger.txt"]
SPDX-FileCopyrightText = "Caleb Maclennan, Johann Klähn, Stefan Karrmann, Wolfgang Oertl"
SPDX-License-Identifier = "GPL-2.0-or-later"
[[annotations]]
path = [
".editorconfig",
".github/**/*.yml",
".gitignore",
".vintrc.yaml",
"Justfile",
]
SPDX-FileCopyrightText = "Caleb Maclennan, Johann Klähn, Stefan Karrmann, Wolfgang Oertl"
SPDX-License-Identifier = "0BSD"
[[annotations]]
path = ["README.md", "spec/*.ledger", "spec/*.vader", "test/*.journal"]
SPDX-FileCopyrightText = "Caleb Maclennan, Johann Klähn, Stefan Karrmann, Wolfgang Oertl"
SPDX-License-Identifier = "CC0-1.0"

File diff suppressed because it is too large Load Diff

View File

@@ -1,29 +1,45 @@
" Vim Compiler File
" Compiler: ledger
" by Johann Klähn; Use according to the terms of the GPL>=2.
" vim:ts=2:sw=2:sts=2:foldmethod=marker
" SPDX-FileCopyrightText: © 2019 Caleb Maclennan <caleb@alerque.com>
" SPDX-FileCopyrightText: © 2009 Johann Klähn <kljohann@gmail.com>
" SPDX-FileCopyrightText: © 2009 Stefan Karrmann
" SPDX-FileCopyrightText: © 2005 Wolfgang Oertl
" SPDX-License-Identifier: GPL-2.0-or-later
if exists("current_compiler")
scriptencoding utf-8
call ledger#init()
if exists('current_compiler')
finish
endif
let current_compiler = "ledger"
if exists(":CompilerSet") != 2
let current_compiler = b:ledger_bin
if exists(':CompilerSet') != 2
command -nargs=* CompilerSet setlocal <args>
endif
" default value will be set in ftplugin
if ! exists("g:ledger_bin") || empty(g:ledger_bin) || ! executable(g:ledger_bin)
finish
let s:escaped_bin = substitute(b:ledger_bin, ' ', '\\ ', 'g')
let s:escaped_main = substitute(shellescape(expand(b:ledger_main)), ' ', '\\ ', 'g')
let s:escaped_extra = substitute(b:ledger_extra_options, ' ', '\\ ', 'g')
if !b:ledger_is_hledger
" Capture Ledger errors (%-C ignores all lines between "While parsing..." and "Error:..."):
CompilerSet errorformat=%EWhile\ parsing\ file\ \"%f\"\\,\ line\ %l:,%ZError:\ %m,%-C%.%#
" Capture Ledger warnings:
CompilerSet errorformat+=%tarning:\ \"%f\"\\,\ line\ %l:\ %m
" Skip all other lines:
CompilerSet errorformat+=%-G%.%#
exe 'CompilerSet makeprg='
\.s:escaped_bin
\.'\ -f\ '.s:escaped_main
\.'\ '.s:escaped_extra
\.'\ source\ '.s:escaped_main
else
exe 'CompilerSet makeprg='
\.s:escaped_bin
\.'\ -f\ '.s:escaped_main
\.'\ check\ '.s:escaped_extra
CompilerSet errorformat=hledger:\ %trror:\ %f:%l:%c:
CompilerSet errorformat+=hledger:\ %trror:\ %f:%l:
CompilerSet errorformat+=hledger:\ %trror:\ %f:%l-%.%#:
endif
" Capture Ledger errors (%-C ignores all lines between "While parsing..." and "Error:..."):
CompilerSet errorformat=%EWhile\ parsing\ file\ \"%f\"\\,\ line\ %l:,%ZError:\ %m,%-C%.%#
" Capture Ledger warnings:
CompilerSet errorformat+=%tarning:\ \"%f\"\\,\ line\ %l:\ %m
" Skip all other lines:
CompilerSet errorformat+=%-G%.%#
" Check file syntax
exe 'CompilerSet makeprg='.substitute(g:ledger_bin, ' ', '\\ ', 'g').'\ '.substitute(g:ledger_extra_options, ' ', '\\ ', 'g').'\ source\ %:S'

View File

@@ -47,10 +47,14 @@ Tips and useful commands
:silent make | redraw! | cwindow
It is recommended to set the value of `g:ledger_extra_options` (see below)
as follows:
as follows for ledger:
let g:ledger_extra_options = '--pedantic --explicit --check-payees'
and as follows for hledger:
let g:ledger_extra_options = '--strict ordereddates payees uniqueleafnames'
to catch most potential problems in your source file.
* Remap vim paragraph motion to move by transaction.
@@ -65,7 +69,7 @@ Tips and useful commands
The default definitions already work in ledger files that separate
transactions with blank lines.
* `:call ledger#transaction_date_set('.'), "auxiliary")`
* `:call ledger#transaction_date_set(line('.'), "auxiliary")`
will set today's date as the auxiliary date of the current transaction. You
can use also "primary" or "unshift" in place of "auxiliary". When you pass
@@ -87,6 +91,16 @@ Tips and useful commands
noremap <silent><buffer> <2-LeftMouse>\
:call ledger#transaction_state_toggle(line('.'), ' *?!')<CR>
* `:call ledger#transaction_post_state_set(line('.'), '*')`
is similar to ledger#transaction_state_set but can set state of individual
post.
* `:call ledger#transaction_post_state_toggle(line('.'), ' *?!')`
is similar to ledger#transaction_state_toggle but can toggle state of
individual post.
* `:LedgerAlign`
moves the amount expression of a posting so that the decimal separator is
@@ -96,10 +110,29 @@ Tips and useful commands
being the current line.
The decimal separator can be set using `g:ledger_decimal_sep`. The default
value of `g:ledger_decimal_sep` is `'.'`.
value of `g:ledger_decimal_sep` is `'.'`. More than one possible character
may be specified and any matches will count, e.g. `'.,'`.
By default the alignment is done on the first matching decimal separator.
This may be changed by setting `g:ledger_align_last` to `v:true`, in which
case the last possible decimal separator will be used. This is useful for
mixed-currency ledgers where decimal and thousands separators in different
currencies may clash and/or aligning on the right hand side of rate
conversions is desired.
See below for the recommended mappings.
* `:LedgerAlignBuffer`
This command aligns the commodity for each posting in the entire buffer,
similar to the command `:LedgerAlign`. It differs from manually specifying
the entire buffer as the range to `:LedgerAlign` or
`ledger#align_commodity()` by saving and restoring the cursor and window
position.
Due to performance concerns, it is not recommended to call this command
on large buffers.
* `:call ledger#align_amount_at_cursor()`
aligns the amount under the cursor and append/prepend the default currency.
@@ -246,14 +279,111 @@ Configuration
Include the following let-statements somewhere in your `.vimrc` to modify the
behaviour of the ledger filetype.
=== Ledger / HLedger Configuration ===
* Path to the `ledger` executable:
let g:ledger_bin = 'ledger'
* Whether to use ledger or hledger specific features. Setting this value is
optional and in most cases will be guessed correctly based on g:ledger_bin,
but in the event it isn't guessed correctly or you want to use different
syntax features even with your default tooling setup for the other engine
this flag can be set to override the value.
let g:ledger_is_hledger = v:true
* Additional default options for the `ledger` executable:
let g:ledger_extra_options = ''
* The file to be used to generate reports:
let g:ledger_main = '%:p'
The default is to use the current file.
* Disable automatic detection and use of ledger binary:
let g:ledger_no_bin = 1
=== Completion Settings ===
* To use a custom external system command to generate a list of account names
for completion, set the following. If g:ledger_bin is set, this will default
to running that command with arguments to parse the current file using the
accounts subcommand (works with ledger or hledger), otherwise it will parse
the postings in the current file itself.
let g:ledger_accounts_cmd = 'ledger accounts'
* To use a custom external system command to generate a list of descriptions
for completion, set the following. If g:ledger_bin is set, this will default
to running that command with arguments to parse the current file using the
descriptions subcommand (works with ledger or hledger), otherwise it will
parse the transactions in the current file itself.
let g:ledger_descriptions_cmd = 'ledger payees'
* If you want account completion based on fuzzy matching instead of the
default sub-level completion:
let g:ledger_fuzzy_account_completion = 1
* If you want the account completion to be sorted by level of detail/depth
instead of alphabetical:
let g:ledger_detailed_first = 1
* Show only exact matches in completion:
let g:ledger_exact_only = 1
* Include the original text in completion results:
let g:ledger_include_original = 1
* Enable spell checking for account names:
let g:ledger_accounts_spell = 1
=== Alignment and Formatting Settings ===
* Specify at which column decimal separators should be aligned:
let g:ledger_align_at = 60
* Decimal separator for alignment:
let g:ledger_decimal_sep = '.'
* Specify alignment on first or last matching separator:
let g:ledger_align_last = v:false
* Default commodity used by `ledger#align_amount_at_cursor()`:
let g:ledger_default_commodity = ''
* Align on the commodity location instead of the amount:
let g:ledger_align_commodity = 1
* Flag that tells whether the commodity should be prepended or appended to the
amount:
let g:ledger_commodity_before = 1
* String to be put between the commodity and the amount:
let g:ledger_commodity_sep = ''
* Enable spell checking for commodity symbols:
let g:ledger_commodity_spell = 1
=== Folding Settings ===
* Number of columns that will be used to display the foldtext. Set this when
you think that the amount is too far off to the right.
@@ -264,11 +394,6 @@ behaviour of the ledger filetype.
let g:ledger_fillstring = ' -'
* If you want the account completion to be sorted by level of detail/depth
instead of alphabetical, include the following line:
let g:ledger_detailed_first = 1
* By default vim will fold ledger transactions, leaving surrounding blank lines
unfolded. You can use 'g:ledger_fold_blanks' to hide blank lines following a
transaction.
@@ -283,40 +408,13 @@ behaviour of the ledger filetype.
folding. You can take advantage of this to disable this feature on a
case-by-case basis.
* Decimal separator:
let g:ledger_decimal_sep = '.'
* Specify at which column decimal separators should be aligned:
let g:ledger_align_at = 60
* Default commodity used by `ledger#align_amount_at_cursor()`:
let g:ledger_default_commodity = ''
* Flag that tells whether the commodity should be prepended or appended to the
amount:
let g:ledger_commodity_before = 1
* String to be put between the commodity and the amount:
let g:ledger_commodity_sep = ''
* Flag that enable the spelling of the amount:
let g:ledger_commodity_spell = 1
=== Date Format ===
* Format of transaction date:
let g:ledger_date_format = '%Y/%m/%d'
* The file to be used to generate reports:
let g:ledger_main = '%'
The default is to use the current file.
=== Report Window Settings ===
* Position of a report buffer:
@@ -325,19 +423,7 @@ behaviour of the ledger filetype.
Use `b` for bottom, `t` for top, `l` for left, `r` for right. Use uppercase letters
if you want the window to always occupy the full width or height.
* Format of quickfix register reports (see |:Register|):
let g:ledger_qf_register_format = \
'%(date) %-50(payee) %-30(account) %15(amount) %15(total)\n'
The format is specified using the standard Ledger syntax for --format.
* Format of the reconcile quickfix window (see |:Reconcile|):
let g:ledger_qf_reconcile_format = \
'%(date) %-4(code) %-50(payee) %-30(account) %15(amount)\n'
The format is specified using the standard Ledger syntax for --format.
=== Quickfix Window Settings ===
* Flag that tells whether a location list or a quickfix list should be used:
@@ -362,8 +448,30 @@ behaviour of the ledger filetype.
let g:ledger_qf_hide_file = 1
Filenames in the quickfix window are hidden by default. Set this to 1 is
you want filenames to be visible.
Filenames in the quickfix window are hidden by default. Set this to 0
if you want filenames to be visible.
* Format of quickfix register reports (see |:Register|):
let g:ledger_qf_register_format =
\ '%(date) %(justify(payee, 50)) '.
\ '%(justify(account, 30)) %(justify(amount, 15, -1, true)) '.
\ '%(justify(total, 15, -1, true))\n'
The format is specified using the standard Ledger syntax for --format.
* Format of the reconcile quickfix window (see |:Reconcile|):
let g:ledger_qf_reconcile_format =
\ '%(date) %(justify(code, 4)) '.
\ '%(justify(payee, 50)) %(justify(account, 30)) '.
\ '%(justify(amount, 15, -1, true))\n'
The format is specified using the standard Ledger syntax for --format.
Note that Reconcile is only available with Ledger, not HLedger.
=== Balance Display Settings ===
* Text of the output of the |:Balance| command:
@@ -371,6 +479,14 @@ behaviour of the ledger filetype.
let g:ledger_pending_string = 'Cleared or pending: '
let g:ledger_target_string = 'Difference from target: '
=== Advanced Settings ===
* Enable automatic formatting with the ledger binary (potentially dangerous):
let g:ledger_dangerous_formatprg = 1
WARNING: This feature can cause data loss when run on non-transaction blocks.
==============================================================================
COMPLETION *ledger-completion*
@@ -378,8 +494,8 @@ Omni completion is currently implemented for account names only.
### Accounts
Account names are matched by the start of every sub-level. When you
insert an account name like this:
By default, account names are matched by the start of every sub-level. When
you insert an account name like this:
Asse<C-X><C-O>
@@ -391,6 +507,16 @@ Go ahead and try something like:
When you have an account like this, 'Assets:Bank:Checking' should show up.
If fuzzy matching based account completion is enabled, the matches are
loaded based on string similarity and without regard for the sub-levels.
In the previous example, with fuzzy matching enabled, you could load up
matches by doing something like:
Chec<C-X><C-O>
Notice that we did not need to write the initial account components.
When you want to complete on a virtual transaction, it's currently best
to keep the cursor in front of the closing bracket. Of course you can
insert the closing bracket after calling the completion, too.
@@ -400,7 +526,7 @@ LICENSE *ledger-license*
https://github.com/ledger/vim-ledger
Copyright 2019 Caleb Maclennan
Copyright 20192025 Caleb Maclennan
Copyright 20092017 Johann Klähn
Copyright 2009 Stefan Karrmann
Copyright 2005 Wolfgang Oertl

View File

@@ -1 +1,17 @@
autocmd BufNewFile,BufRead *.ldg,*.ledger,*.journal setlocal filetype=ledger
" SPDX-FileCopyrightText: © 2019 Caleb Maclennan <caleb@alerque.com>
" SPDX-FileCopyrightText: © 2009 Johann Klähn <kljohann@gmail.com>
" SPDX-FileCopyrightText: © 2009 Stefan Karrmann
" SPDX-FileCopyrightText: © 2005 Wolfgang Oertl
" SPDX-License-Identifier: GPL-2.0-or-later
scriptencoding utf-8
augroup ledger_file_detection
autocmd!
" Semi-canonical or common file extensions
autocmd BufNewFile,BufRead *.journal,*.ledger,*.hledger setfiletype ledger
" Deprecated or suspiciusly low usage extensions
" TODO: Consider hiding these behind an off-by-default config flag
autocmd BufNewFile,BufRead *.ldg,*.j, setfiletype ledger
augroup END

View File

@@ -1,194 +1,82 @@
" Vim filetype plugin file
" filetype: ledger
" by Johann Klähn; Use according to the terms of the GPL>=2.
" vim:ts=2:sw=2:sts=2:foldmethod=marker
" SPDX-FileCopyrightText: © 2019 Caleb Maclennan <caleb@alerque.com>
" SPDX-FileCopyrightText: © 2009 Johann Klähn <kljohann@gmail.com>
" SPDX-FileCopyrightText: © 2009 Stefan Karrmann
" SPDX-FileCopyrightText: © 2005 Wolfgang Oertl
" SPDX-License-Identifier: GPL-2.0-or-later
if exists("b:did_ftplugin")
scriptencoding utf-8
call ledger#init()
if exists('b:did_ftplugin')
finish
endif
let b:did_ftplugin = 1
let b:undo_ftplugin = "setlocal ".
\ "foldtext< ".
\ "include< comments< commentstring< omnifunc< formatprg<"
let b:undo_ftplugin = 'setlocal '.
\ 'foldtext< '.
\ 'include< comments< commentstring< omnifunc< formatexpr< formatprg<'
setlocal foldtext=LedgerFoldText()
setlocal include=^!\\?include
setlocal comments=b:;
setlocal commentstring=;%s
setlocal omnifunc=LedgerComplete
setlocal formatexpr=ledger#align_formatexpr(v:lnum,v:count)
" Automatic formatting is disabled by default because it can cause data loss when run
" on non-transaction blocks, see https://github.com/ledger/vim-ledger/issues/168.
if b:ledger_dangerous_formatprg
execute 'setlocal formatprg='.substitute(b:ledger_bin, ' ', '\\ ', 'g').'\ -f\ -\ print'
endif
if !exists('current_compiler')
compiler ledger
endif
setl foldtext=LedgerFoldText()
setl include=^!\\?include
setl comments=b:;
setl commentstring=;%s
setl omnifunc=LedgerComplete
" Highlight groups for Ledger reports
highlight default link LedgerNumber Number
highlight default link LedgerNegativeNumber Special
highlight default link LedgerCleared Constant
highlight default link LedgerPending Todo
highlight default link LedgerTarget Statement
highlight default link LedgerImproperPerc Special
" set location of ledger binary for checking and auto-formatting
if ! exists("g:ledger_bin") || empty(g:ledger_bin) || ! executable(g:ledger_bin)
if executable('ledger')
let g:ledger_bin = 'ledger'
else
unlet! g:ledger_bin
echohl WarningMsg
echomsg "ledger command not found. Set g:ledger_bin or extend $PATH ".
\ "to enable error checking and auto-formatting."
echohl None
endif
endif
let s:currency_symbol = '[[:alpha:]¢$€£]\+'
let s:value_regex = '\('.
\ '\%([0-9]\+\)'.
\ '\%([,.][0-9]\+\)*'.
\ '\|'.
\ '[,.][0-9]\+'.
\ '\)'
let s:optional_sign = '[+-]\?'
let s:currency_sign = '\('.
\ s:optional_sign.
\ '\s*'.
\ s:currency_symbol.
\ '\|'.
\ s:currency_symbol.
\ '\s*'.
\ s:optional_sign.
\ '\)'
if exists("g:ledger_bin")
exe 'setl formatprg='.substitute(g:ledger_bin, ' ', '\\ ', 'g').'\ -f\ -\ print'
endif
let s:optional_balance_assertion = '\(\s*=\s*'.s:currency_sign.'\s*'.s:value_regex.'\)\?'
if !exists('g:ledger_extra_options')
let g:ledger_extra_options = ''
endif
if !exists('g:ledger_date_format')
let g:ledger_date_format = '%Y/%m/%d'
endif
" You can set a maximal number of columns the fold text (excluding amount)
" will use by overriding g:ledger_maxwidth in your .vimrc.
" When maxwidth is zero, the amount will be displayed at the far right side
" of the screen.
if !exists('g:ledger_maxwidth')
let g:ledger_maxwidth = 0
endif
if !exists('g:ledger_fillstring')
let g:ledger_fillstring = ' '
endif
if !exists('g:ledger_decimal_sep')
let g:ledger_decimal_sep = '.'
endif
if !exists('g:ledger_align_at')
let g:ledger_align_at = 60
endif
if !exists('g:ledger_default_commodity')
let g:ledger_default_commodity = ''
endif
if !exists('g:ledger_commodity_before')
let g:ledger_commodity_before = 1
endif
if !exists('g:ledger_commodity_sep')
let g:ledger_commodity_sep = ''
endif
" If enabled this will list the most detailed matches at the top {{{
" of the completion list.
" For example when you have some accounts like this:
" A:Ba:Bu
" A:Bu:Bu
" and you complete on A:B:B normal behaviour may be the following
" A:B:B
" A:Bu:Bu
" A:Bu
" A:Ba:Bu
" A:Ba
" A
" with this option turned on it will be
" A:B:B
" A:Bu:Bu
" A:Ba:Bu
" A:Bu
" A:Ba
" A
" }}}
if !exists('g:ledger_detailed_first')
let g:ledger_detailed_first = 1
endif
" only display exact matches (no parent accounts etc.)
if !exists('g:ledger_exact_only')
let g:ledger_exact_only = 0
endif
" display original text / account name as completion
if !exists('g:ledger_include_original')
let g:ledger_include_original = 0
endif
" Settings for Ledger reports {{{
if !exists('g:ledger_main')
let g:ledger_main = '%'
endif
if !exists('g:ledger_winpos')
let g:ledger_winpos = 'B' " Window position (see s:winpos_map)
endif
if !exists('g:ledger_use_location_list')
let g:ledger_use_location_list = 0 " Use quickfix list by default
endif
if !exists('g:ledger_cleared_string')
let g:ledger_cleared_string = 'Cleared: '
endif
if !exists('g:ledger_pending_string')
let g:ledger_pending_string = 'Cleared or pending: '
endif
if !exists('g:ledger_target_string')
let g:ledger_target_string = 'Difference from target: '
endif
" }}}
" Settings for the quickfix window {{{
if !exists('g:ledger_qf_register_format')
let g:ledger_qf_register_format = '%(date) %-50(payee) %-30(account) %15(amount) %15(total)\n'
endif
if !exists('g:ledger_qf_reconcile_format')
let g:ledger_qf_reconcile_format = '%(date) %-4(code) %-50(payee) %-30(account) %15(amount)\n'
endif
if !exists('g:ledger_qf_size')
let g:ledger_qf_size = 10 " Size of the quickfix window
endif
if !exists('g:ledger_qf_vertical')
let g:ledger_qf_vertical = 0
endif
if !exists('g:ledger_qf_hide_file')
let g:ledger_qf_hide_file = 1
endif
" }}}
" Highlight groups for Ledger reports {{{
hi link LedgerNumber Number
hi link LedgerNegativeNumber Special
hi link LedgerCleared Constant
hi link LedgerPending Todo
hi link LedgerTarget Statement
hi link LedgerImproperPerc Special
" }}}
let s:rx_amount = '\('.
\ '\%([0-9]\+\)'.
\ '\%([,.][0-9]\+\)*'.
\ '\|'.
\ '[,.][0-9]\+'.
\ '\)'.
\ '\s*\%([[:alpha:]¢$€£]\+\s*\)\?'.
let s:rx_amount = s:value_regex.
\ s:optional_balance_assertion.
\ '\s*\%('.s:currency_symbol.'\s*\)\?'.
\ '\%(\s*;.*\)\?$'
function! LedgerFoldText() "{{{1
function! LedgerFoldText()
" find amount
let amount = ""
let lnum = v:foldstart + 1
while lnum <= v:foldend
let line = getline(lnum)
let amount = ''
let line_number = v:foldstart + 1
while line_number <= v:foldend
let line = getline(line_number)
" Skip metadata/leading comment
if line !~ '^\%(\s\+;\|\d\)'
if line !~# '^\%(\s\+;\|\d\)'
" No comment, look for amount...
let groups = matchlist(line, s:rx_amount)
if ! empty(groups)
@@ -196,80 +84,114 @@ function! LedgerFoldText() "{{{1
break
endif
endif
let lnum += 1
let line_number += 1
endwhile
let fmt = '%s %s '
" strip whitespace at beginning and end of line
let foldtext = substitute(getline(v:foldstart),
\ '\(^\s\+\|\s\+$\)', '', 'g')
" number of columns foldtext can use
let columns = s:get_columns()
if g:ledger_maxwidth
let columns = min([columns, g:ledger_maxwidth])
if b:ledger_maxwidth
let columns = min([columns, b:ledger_maxwidth])
endif
let columns -= s:multibyte_strlen(printf(fmt, '', amount))
" add spaces so the text is always long enough when we strip it
" to a certain width (fake table)
if strlen(g:ledger_fillstring)
" add extra spaces so fillstring aligns
let filen = s:multibyte_strlen(g:ledger_fillstring)
let folen = s:multibyte_strlen(foldtext)
let foldtext .= repeat(' ', filen - (folen%filen))
let amount = printf(' %s ', amount)
" left cut-off if window is too narrow to display the amount
while columns < strdisplaywidth(amount)
let amount = substitute(amount, '^.', '', '')
endwhile
let columns -= strdisplaywidth(amount)
let foldtext .= repeat(g:ledger_fillstring,
\ s:get_columns()/filen)
if columns <= 0
return amount
endif
" right cut-off if there is not sufficient space to display the description
while columns < strdisplaywidth(foldtext)
let foldtext = substitute(foldtext, '.$', '', '')
endwhile
let columns -= strdisplaywidth(foldtext)
if columns <= 0
return foldtext . amount
endif
" fill in the fillstring
if strlen(b:ledger_fillstring)
let fillstring = b:ledger_fillstring
else
let foldtext .= repeat(' ', s:get_columns())
let fillstring = ' '
endif
let fillstrlen = strdisplaywidth(fillstring)
" we don't use slices[:5], because that messes up multibyte characters
let foldtext = substitute(foldtext, '.\{'.columns.'}\zs.*$', '', '')
let foldtext .= ' '
let columns -= 1
while columns >= fillstrlen
let foldtext .= fillstring
let columns -= fillstrlen
endwhile
return printf(fmt, foldtext, amount)
endfunction "}}}
while columns < strdisplaywidth(fillstring)
let fillstring = substitute(fillstring, '.$', '', '')
endwhile
let foldtext .= fillstring
function! LedgerComplete(findstart, base) "{{{1
return foldtext . amount
endfunction
function! LedgerComplete(findstart, base)
if a:findstart
let lnum = line('.')
let line_number = line('.')
let line = getline('.')
let b:compl_context = ''
if line =~ '^\s\+[^[:blank:];]' "{{{2 (account)
let b:completion_context = ''
if line =~# '^\s\+[^[:blank:];]'
" only allow completion when in or at end of account name
if matchend(line, '^\s\+\%(\S \S\|\S\)\+') >= col('.') - 1
" the start of the first non-blank character
" (excluding virtual-transaction and 'cleared' marks)
" is the beginning of the account name
let b:compl_context = 'account'
let b:completion_context = 'account'
return matchend(line, '^\s\+[*!]\?\s*[\[(]\?')
endif
elseif line =~ '^\d' "{{{2 (description)
let pre = matchend(line, '^\d\S\+\%(([^)]*)\|[*?!]\|\s\)\+')
if pre < col('.') - 1
let b:compl_context = 'description'
return pre
elseif line =~# '^account '
let prefix = matchend(line, '^account ')
let b:completion_context = 'account'
return prefix
elseif line =~# '^\d'
let prefix = matchend(line, '^\d\S\+\%\(\s\(([^\)]*)\|[*?!]\)\)\?\s\+')
if prefix <= col('.') - 1
let b:completion_context = 'description'
if prefix == -1
return -3
endif
return prefix
endif
elseif line =~ '^$' "{{{2 (new line)
let b:compl_context = 'new'
endif "}}}
return -1
elseif b:ledger_is_hledger && line =~# '^payee '
let prefix = matchend(line, '^payee ')
let b:completion_context = 'description'
return prefix
elseif line =~# '^$'
let b:completion_context = 'new'
return 0
endif
return -3
else
if ! exists('b:compl_cache')
let b:compl_cache = s:collect_completion_data()
let b:compl_cache['#'] = changenr()
if ! exists('b:completion_cache')
let b:completion_cache = s:collect_completion_data()
let b:completion_cache['#'] = changenr()
endif
let update_cache = 0
let results = []
if b:compl_context == 'account' "{{{2 (account)
if b:completion_context ==# 'account'
let hierarchy = split(a:base, ':')
if a:base =~ ':$'
if a:base =~# ':$'
call add(hierarchy, '')
endif
let results = ledger#find_in_tree(b:compl_cache.accounts, hierarchy)
let results = ledger#find_in_tree(b:completion_cache.accounts, hierarchy)
let exacts = filter(copy(results), 'v:val[1]')
if len(exacts) < 1
@@ -277,82 +199,72 @@ function! LedgerComplete(findstart, base) "{{{1
let update_cache = 1
endif
if g:ledger_exact_only
if b:ledger_exact_only
let results = exacts
endif
call map(results, 'v:val[0]')
if g:ledger_detailed_first
if b:ledger_fuzzy_account_completion
let results = matchfuzzy(b:completion_cache.flat_accounts, a:base, {'matchseq':1})
elseif b:ledger_detailed_first
let results = reverse(sort(results, 's:sort_accounts_by_depth'))
else
let results = sort(results)
endif
elseif b:compl_context == 'description' "{{{2 (description)
let results = ledger#filter_items(b:compl_cache.descriptions, a:base)
elseif b:completion_context ==# 'description'
let results = ledger#filter_items(b:completion_cache.descriptions, a:base)
if len(results) < 1
let update_cache = 1
endif
elseif b:compl_context == 'new' "{{{2 (new line)
return [strftime(g:ledger_date_format)]
endif "}}}
elseif b:completion_context ==# 'new'
return [strftime(b:ledger_date_format)]
endif
if g:ledger_include_original
if b:ledger_include_original
call insert(results, a:base)
endif
" no completion (apart from a:base) found. update cache if file has changed
if update_cache && b:compl_cache['#'] != changenr()
unlet b:compl_cache
if update_cache && b:completion_cache['#'] != changenr()
unlet b:completion_cache
return LedgerComplete(a:findstart, a:base)
else
unlet! b:compl_context
unlet! b:completion_context
return results
endif
endif
endf "}}}
endfunction
" Deprecated functions {{{1
let s:deprecated = {
\ 'LedgerToggleTransactionState': 'ledger#transaction_state_toggle',
\ 'LedgerSetTransactionState': 'ledger#transaction_state_set',
\ 'LedgerSetDate': 'ledger#transaction_date_set'
\ }
for [s:old, s:new] in items(s:deprecated)
let s:fun = "function! {s:old}(...)\nechohl WarningMsg\necho '" . s:old .
\ " is deprecated. Use ".s:new." instead!'\nechohl None\n" .
\ "call call('" . s:new . "', a:000)\nendf"
exe s:fun
endfor
unlet s:old s:new s:fun
" }}}1
function! s:collect_completion_data() "{{{1
function! s:collect_completion_data()
let transactions = ledger#transactions()
let cache = {'descriptions': [], 'tags': {}, 'accounts': {}}
let accounts = ledger#declared_accounts()
for xact in transactions
" collect descriptions
if has_key(xact, 'description') && index(cache.descriptions, xact['description']) < 0
call add(cache.descriptions, xact['description'])
endif
let [t, postings] = xact.parse_body()
let tagdicts = [t]
let cache = {'descriptions': [], 'tags': {}, 'accounts': {}, 'flat_accounts': []}
" collect account names
for posting in postings
if has_key(posting, 'tags')
call add(tagdicts, posting.tags)
endif
" remove virtual-transaction-marks
let name = substitute(posting.account, '\%(^\s*[\[(]\?\|[\])]\?\s*$\)', '', 'g')
if index(accounts, name) < 0
call add(accounts, name)
endif
endfor
let accounts = s:get_accounts_list()
let cache.flat_accounts = accounts
let cache.descriptions = s:get_descriptions_list()
for transaction in transactions
let [tags, postings] = transaction.parse_body()
let tagdicts = [tags]
" collect account names (only when not using ledger binary)
if b:ledger_bin ==# v:false
for posting in postings
if has_key(posting, 'tags')
call add(tagdicts, posting.tags)
endif
" remove virtual-transaction-marks
let name = substitute(posting.account, '^\s*|\s*$', '', 'g')
let name = substitute(name, '^(.*)$', '\1', '')
let name = substitute(name, '^\[.*\]$', '\1', '')
if index(accounts, name) < 0
call add(accounts, name)
endif
endfor
endif
" collect tags
for tags in tagdicts | for [tag, val] in items(tags)
@@ -373,17 +285,35 @@ function! s:collect_completion_data() "{{{1
endfor
return cache
endf "}}}
endfunction
" Helper functions {{{1
function! s:get_accounts_list()
if b:ledger_bin !=# v:false
return split(system(b:ledger_accounts_cmd), '\n')
else
return ledger#declared_accounts()
endif
endfunction
" return length of string with fix for multibyte characters
function! s:multibyte_strlen(text) "{{{2
return strlen(substitute(a:text, ".", "x", "g"))
endfunction "}}}
function! s:get_descriptions_list()
if b:ledger_bin !=# v:false
return split(system(b:ledger_descriptions_cmd), '\n')
else
let transactions = ledger#transactions()
let descriptions = []
for xact in transactions
if has_key(xact, 'description') && index(descriptions, xact['description']) < 0
call add(descriptions, xact['description'])
endif
endfor
return descriptions
endif
endfunction
" Helper functions
" get # of visible/usable columns in current window
function! s:get_columns() " {{{2
function! s:get_columns()
" As long as vim doesn't provide a command natively,
" we have to compute the available columns.
" see :help todo.txt -> /Add argument to winwidth()/
@@ -396,54 +326,56 @@ function! s:get_columns() " {{{2
" are there any signs/is the sign column displayed?
redir => signs
silent execute 'sign place buffer='.string(bufnr("%"))
silent execute 'sign place buffer='.string(bufnr('%'))
redir END
if signs =~# 'id='
let columns -= 2
endif
return columns
endf "}}}
endfunction
function! s:sort_accounts_by_depth(name1, name2) "{{{2
function! s:sort_accounts_by_depth(name1, name2)
let depth1 = s:count_expression(a:name1, ':')
let depth2 = s:count_expression(a:name2, ':')
return depth1 == depth2 ? 0 : depth1 > depth2 ? 1 : -1
endf "}}}
endfunction
function! s:count_expression(text, expression) "{{{2
function! s:count_expression(text, expression)
return len(split(a:text, a:expression, 1))-1
endf "}}}
endfunction
function! s:autocomplete_account_or_payee(argLead, cmdLine, cursorPos) "{{{2
return (a:argLead =~ '^@') ?
\ map(filter(systemlist(g:ledger_bin . ' -f ' . shellescape(expand(g:ledger_main)) . ' payees'),
\ "v:val =~? '" . strpart(a:argLead, 1) . "' && v:val !~? '^Warning: '"), '"@" . escape(v:val, " ")')
\ :
\ map(filter(systemlist(g:ledger_bin . ' -f ' . shellescape(expand(g:ledger_main)) . ' accounts'),
\ "v:val =~? '" . a:argLead . "' && v:val !~? '^Warning: '"), 'escape(v:val, " ")')
endf "}}}
function! s:autocomplete_account_or_payee(argument_lead, command_line, cursor_position)
if a:argument_lead =~# '^@'
let payees = s:get_descriptions_list()
let pattern = strpart(a:argument_lead, 1)
return map(filter(payees, "v:val =~? '" . pattern . "' && v:val !~? '^Warning: '"),
\ '"@" . escape(v:val, " ")')
else
let accounts = s:get_accounts_list()
return map(filter(accounts, "v:val =~? '" . a:argument_lead . "' && v:val !~? '^Warning: '"),
\ 'escape(v:val, " ")')
endif
endfunction
function! s:reconcile(file, account) "{{{2
" call inputsave()
let l:amount = input('Target amount' . (empty(g:ledger_default_commodity) ? ': ' : ' (' . g:ledger_default_commodity . '): '))
" call inputrestore()
function! s:reconcile(file, account)
let l:amount = input('Target amount' . (empty(b:ledger_default_commodity) ? ': ' : ' (' . b:ledger_default_commodity . '): '))
call ledger#reconcile(a:file, a:account, str2float(l:amount))
endf "}}}
endfunction
" Commands {{{1
command! -buffer -nargs=? -complete=customlist,s:autocomplete_account_or_payee
\ Balance call ledger#show_balance(g:ledger_main, <q-args>)
" Commands
command! -buffer -nargs=? -complete=customlist,<SID>autocomplete_account_or_payee
\ Balance call ledger#show_balance(b:ledger_main, <q-args>)
command! -buffer -nargs=+ -complete=customlist,s:autocomplete_account_or_payee
\ Ledger call ledger#output(ledger#report(g:ledger_main, <q-args>))
command! -buffer -nargs=+ -complete=customlist,<SID>autocomplete_account_or_payee
\ Ledger call ledger#output(ledger#report(b:ledger_main, <q-args>))
command! -buffer -range LedgerAlign <line1>,<line2>call ledger#align_commodity()
command! -buffer -nargs=1 -complete=customlist,s:autocomplete_account_or_payee
\ Reconcile call <sid>reconcile(g:ledger_main, <q-args>)
command! -buffer LedgerAlignBuffer call ledger#align_commodity_buffer()
command! -buffer -complete=customlist,s:autocomplete_account_or_payee -nargs=*
\ Register call ledger#register(g:ledger_main, <q-args>)
" }}}
command! -buffer -nargs=1 -complete=customlist,<SID>autocomplete_account_or_payee
\ Reconcile call <SID>reconcile(b:ledger_main, <q-args>)
command! -buffer -complete=customlist,<SID>autocomplete_account_or_payee -nargs=*
\ Register call ledger#register(b:ledger_main, <q-args>)

View File

@@ -1,17 +1,23 @@
" Vim filetype indent file
" filetype: ledger
" by Johann Klähn; Use according to the terms of the GPL>=2.
" vim:ts=2:sw=2:sts=2:foldmethod=marker
" SPDX-FileCopyrightText: © 2019 Caleb Maclennan <caleb@alerque.com>
" SPDX-FileCopyrightText: © 2009 Johann Klähn <kljohann@gmail.com>
" SPDX-FileCopyrightText: © 2009 Stefan Karrmann
" SPDX-FileCopyrightText: © 2005 Wolfgang Oertl
" SPDX-License-Identifier: GPL-2.0-or-later
if exists("b:did_indent")
scriptencoding utf-8
call ledger#init()
if exists('b:did_indent')
finish
endif
let b:did_indent = 1
setl autoindent
setl indentexpr=GetLedgerIndent()
setlocal autoindent
setlocal indentexpr=GetLedgerIndent()
if exists("*GetLedgerIndent")
if exists('*GetLedgerIndent')
finish
endif
@@ -23,18 +29,18 @@ function GetLedgerIndent(...)
let line = getline(lnum)
let prev = getline(lnum - 1)
if line =~ '^\s\+\S'
if line =~# '^\s\+\S'
" Lines that already are indented (→postings, sub-directives) keep their indentation.
return &sw
elseif line =~ '^\s*$'
return shiftwidth()
elseif line =~# '^\s*$'
" Current line is empty, try to guess its type based on the previous line.
if prev =~ '^\([[:digit:]~=]\|\s\+\S\)'
if prev =~# '^\([[:digit:]~=]\|\s\+\S\)'
" This is very likely a posting or a sub-directive.
" While lines following the start of a transaction are automatically
" indented you will have to indent the first line following a
" pre-declaration manually. This makes it easier to type long lists of
" 'account' pre-declarations without sub-directives, for example.
return &sw
return shiftwidth()
else
return 0
endif
@@ -43,4 +49,4 @@ function GetLedgerIndent(...)
" start of transactions, pre-declarations, apply/end-lines
return 0
endif
endf
endfunction

View File

@@ -0,0 +1,31 @@
Given ledger:
1970-01-01 Person
Expenses $6.00
Cash
Execute (align buffer):
LedgerAlignBuffer
Expect ledger:
1970-01-01 Person
Expenses $6.00
Cash
Execute (align buffer on commodity):
let b:ledger_align_commodity = 1
LedgerAlignBuffer
Expect ledger:
1970-01-01 Person
Expenses $6.00
Cash
Execute (change default alignment):
let b:ledger_align_commodity = 0
let b:ledger_align_at = 40
LedgerAlignBuffer
Expect ledger:
1970-01-01 Person
Expenses $6.00
Cash

View File

@@ -0,0 +1,8 @@
Execute:
file spec/ledger.ledger
Ledger accounts
Expect ledger:
Cash
Expenses

View File

@@ -0,0 +1,95 @@
# Here is the main syntax of hledger's journal format
# (omitting extra Ledger compatibility syntax).
# hledger journals contain comments, directives, and transactions, in any order:
###############################################################################
# 1. Comment lines are for notes or temporarily disabling things.
# They begin with #, ;, or a line containing the word "comment".
# hash comment line
; semicolon comment line
comment
These lines
are commented.
end comment
# Some but not all hledger entries can have same-line comments attached to them,
# from ; (semicolon) to end of line.
###############################################################################
# 2. Directives modify parsing or reports in some way.
# They begin with a word or letter (or symbol).
account actifs ; type:A, declare an account that is an Asset. 2+ spaces before ;.
account passifs ; type:L, declare an account that is a Liability, and so on.. (ALERX)
alias chkg = assets:checking
commodity $0.00
decimal-mark .
include /dev/null
payee Whole Foods
P 2022-01-01 AAAA $1.40
~ monthly budget goals ; <- 2+ spaces between period expression and description
expenses:food $400
expenses:home $1000
budgeted
###############################################################################
# 3. Transactions are what it's all about; they are dated events,
# usually describing movements of money.
# They begin with a date.
# DATE DESCRIPTION ; This is a transaction comment.
# ACCOUNT NAME 1 AMOUNT1 ; <- posting 1. This is a posting comment.
# ACCOUNT NAME 2 AMOUNT2 ; <- posting 2. Postings must be indented.
# ; ^^ At least 2 spaces between account and amount.
# ... ; Any number of postings is allowed. The amounts must balance (sum to 0).
2022-01-01 opening balances are declared this way
assets:checking $1000 ; Account names can be anything. lower case is easy to type.
assets:savings $1000 ; assets, liabilities, equity, revenues, expenses are common.
assets:cash:wallet $100 ; : indicates subaccounts.
liabilities:credit card $-200 ; liabilities, equity, revenues balances are usually negative.
equity ; One amount can be left blank; $-1900 is inferred here.
2022-04-15 * (#12345) pay taxes
; There can be a ! or * after the date meaning "pending" or "cleared".
; There can be a transaction code (text in parentheses) after the date/status.
; Amounts' sign represents direction of flow, or credit/debit:
assets:checking $-500 ; minus means removed from this account (credit)
expenses:tax:us:2021 $500 ; plus means added to this account (debit)
; revenue/expense categories are also "accounts"
2022-01-01 Whole Foods | payee name and description can be separated by a pipe char
; Transaction or posting comments can contain searchable tags,
; written NAME: or NAME:VALUE (value ends at comma or end of line).
; Here's tag1:with a value, and an empty tag2:
; A few tags have special meaning. A "date:" tag on a posting adjusts its date.
assets:checking $-50 ; date:2022-01-03, checking cleared two days later
expenses:food
2022-01-01 ; The description is optional.
; Any currency/commodity symbols are allowed, on either side.
assets:cash:wallet GBP -10
expenses:clothing GBP 10
assets:gringotts -10 gold
assets:pouch 10 gold
revenues:gifts -2 "Liquorice Wands" ; Complex symbols
assets:bag 2 "Liquorice Wands" ; must be double-quoted.
2022-01-01 Cost in another commodity can be noted with @ or @@
assets:investments 2.0 AAAA @ $1.50 ; @ means per-unit cost
assets:investments 3.0 AAAA @@ $4 ; @@ means total cost
assets:checking $-7.00
2022-01-02 assert balances
; Balances can be asserted for extra error checking, in any transaction.
assets:investments 0 AAAA = 5.0 AAAA
assets:pouch 0 gold = 10 gold
assets:savings $0 = $1000
1999-12-31 Ordering transactions by date is recommended but not required.
; Postings are not required.
2022.01.01 These date
2022/1/1 formats are
12/31 also allowed (but consistent YYYY-MM-DD is recommended).

View File

@@ -0,0 +1,3 @@
1970-01-01 Person
Expenses $6.00
Cash

View File

@@ -0,0 +1,78 @@
Given ledger:
2020-03-06 Buy
Expenses $10.00
Cash
Execute (set state):
2
call ledger#transaction_post_state_set(line('.'), '*')
Expect ledger:
2020-03-06 Buy
* Expenses $10.00
Cash
Execute (clear state):
2
call ledger#transaction_post_state_set(line('.'), '*')
call ledger#transaction_post_state_set(line('.'), '')
Expect ledger:
2020-03-06 Buy
Expenses $10.00
Cash
Execute (clear already clear state):
2
call ledger#transaction_post_state_set(line('.'), '')
Expect ledger:
2020-03-06 Buy
Expenses $10.00
Cash
Execute (toggle state):
2
call ledger#transaction_post_state_toggle(line('.'), '!* ')
Expect ledger:
2020-03-06 Buy
! Expenses $10.00
Cash
Execute (toggle state x2):
2
call ledger#transaction_post_state_toggle(line('.'), '!* ')
call ledger#transaction_post_state_toggle(line('.'), '!* ')
Expect ledger:
2020-03-06 Buy
* Expenses $10.00
Cash
Execute (toggle state x3):
2
call ledger#transaction_post_state_toggle(line('.'), '!* ')
call ledger#transaction_post_state_toggle(line('.'), '!* ')
call ledger#transaction_post_state_toggle(line('.'), '!* ')
Expect ledger:
2020-03-06 Buy
Expenses $10.00
Cash
Execute (fallback to posting):
call ledger#transaction_post_state_toggle(line('.'), '!* ')
Expect ledger:
2020-03-06 ! Buy
Expenses $10.00
Cash
Execute (fallback to posting, clear):
call ledger#transaction_post_state_set(line('.'), ' ')
Expect ledger:
2020-03-06 Buy
Expenses $10.00
Cash

View File

@@ -0,0 +1,41 @@
Given ledger (comment tags):
1970-01-01 payee
; ledger :foo:bar: not
; hledger foo:val, not bar:baz
a 1
b
Before:
let g:ledger_is_hledger = v:true
Execute (hledger tags):
" AssertNotEqual SyntaxAt(2, 16), 'ledgerTag'
" AssertEqual SyntaxAt(3, 12), 'ledgerTransactionMetadata'
" AssertEqual SyntaxAt(3, 13), 'ledgerTag'
" AssertEqual SyntaxAt(3, 16), 'ledgerTagDef'
" AssertEqual SyntaxAt(3, 17), 'ledgerTagValue'
" AssertEqual SyntaxAt(3, 20), 'ledgerTransactionMetadata'
" AssertEqual SyntaxAt(3, 26), 'ledgerTag'
" AssertEqual SyntaxAt(3, 29), 'ledgerTagDef'
" AssertEqual SyntaxAt(3, 30), 'ledgerTagValue'
Before:
let g:ledger_is_hledger = v:false
Execute (hledger tags):
" AssertEqual SyntaxAt(2, 14), 'ledgerTag'
" AssertEqual SyntaxAt(2, 23), 'ledgerTagValue'
" AssertEqual SyntaxAt(3, 12), 'ledgerTransactionMetadata'
" AssertNotEqual SyntaxAt(3, 13), 'ledgerTag'
Before:
let g:ledger_is_hledger = v:true
edit spec/hledger-cheatsheet.ledger
Execute (Hledger cheatsheet syntax):
AssertEqual SyntaxAt(1, 3), 'ledgerComment'
AssertEqual SyntaxAt(67, 39), 'ledgerTag'
AssertEqual SyntaxAt(67, 43), 'ledgerTagDef'
AssertEqual SyntaxAt(67, 44), 'ledgerTagValue'
AssertEqual SyntaxAt(67, 54), 'ledgerPostingMetadata'

View File

@@ -1,29 +1,38 @@
" Vim syntax file
" filetype: ledger
" by Johann Klähn; Use according to the terms of the GPL>=2.
" by Stefan Karrmann; Use according to the terms of the GPL>=2.
" by Wolfgang Oertl; Use according to the terms of the GPL>=2.
" vim:ts=2:sw=2:sts=2:foldmethod=marker
" SPDX-FileCopyrightText: © 2019 Caleb Maclennan <caleb@alerque.com>
" SPDX-FileCopyrightText: © 2009 Johann Klähn <kljohann@gmail.com>
" SPDX-FileCopyrightText: © 2009 Stefan Karrmann
" SPDX-FileCopyrightText: © 2005 Wolfgang Oertl
" SPDX-License-Identifier: GPL-2.0-or-later
if version < 600
syntax clear
elseif exists("b:current_sytax")
scriptencoding utf-8
if exists('b:current_syntax')
finish
endif
" Force old regex engine (:help two-engines)
let s:oe = v:version < 704 ? '' : '\%#=1'
let s:lb1 = v:version < 704 ? '\@<=' : '\@1<='
call ledger#init()
let s:fb = get(g:, 'ledger_fold_blanks', 0)
" Force old regex engine (:help two-engines)
let s:oe = '\%#=1'
let s:lb1 = '\@1<='
let s:line_comment_chars = b:ledger_is_hledger ? ';*#' : ';|*#%'
let s:fb = b:ledger_fold_blanks
let s:skip = s:fb > 0 ? '\|^\n' : ''
if s:fb == 1
let s:skip .= '\n\@!'
endif
let s:ledgerAmount_contains = ''
if get(g:, 'ledger_commodity_spell', 0) == 0
let s:ledgerAmount_contains .= '@NoSpell'
let s:ledgerAmounts_contains = ''
let s:ledgerAccounts_contains = ''
if b:ledger_commodity_spell == 0
let s:ledgerAmounts_contains .= '@NoSpell'
endif
if b:ledger_accounts_spell == 0
let s:ledgerAccounts_contains .= '@NoSpell'
endif
" for debugging
@@ -32,76 +41,113 @@ syntax clear
" DATE[=EDATE] [*|!] [(CODE)] DESC <-- first line of transaction
" ACCOUNT AMOUNT [; NOTE] <-- posting
exe 'syn region ledgerTransaction start=/^[[:digit:]~=]/ '.
\ 'skip=/^\s'. s:skip . '/ end=/^/ fold keepend transparent '.
\ 'contains=ledgerTransactionDate,ledgerMetadata,ledgerPosting,ledgerTransactionExpression'
syn match ledgerTransactionDate /^\d\S\+/ contained
syn match ledgerTransactionExpression /^[=~]\s\+\zs.*/ contained
syn match ledgerPosting /^\s\+[^[:blank:];][^;]*\ze\%($\|;\)/
\ contained transparent contains=ledgerAccount,ledgerAmount,ledgerMetadata
execute 'syntax region ledgerTransaction start=/^[[:digit:]~=]/ '.
\ 'skip=/^\s'. s:skip . '/ end=/^/ fold keepend transparent '.
\ 'contains=ledgerTransactionDate,ledgerTransactionMetadata,ledgerPosting,ledgerTransactionExpression'
syntax match ledgerTransactionDate /^\d\S\+/ contained
syntax match ledgerTransactionExpression /^[=~]\s\+\zs.*/ contained
syntax match ledgerPosting /^\s\+[^[:blank:];].*/
\ contained transparent contains=ledgerAccount,ledgerAmount,ledgerValueExpression,ledgerPostingMetadata
" every space in an account name shall be surrounded by two non-spaces
" every account name ends with a tab, two spaces or the end of the line
exe 'syn match ledgerAccount '.
\ '/'.s:oe.'^\s\+\zs\%(\S'.s:lb1.' \S\|\S\)\+\ze\%( \|\t\|\s*$\)/ contained'
exe 'syn match ledgerAmount '.
\ '/'.s:oe.'\S'.s:lb1.'\%( \|\t\)\s*\zs\%([^;[:space:]]\|\s\+[^;[:space:]]\)\+/ contains='.s:ledgerAmount_contains.' contained'
execute 'syntax match ledgerAccount '.
\ '/'.s:oe.'^\s\+\zs\%(\S'.s:lb1.' \S\|\S\)\+\ze\%( \|\t\|\s*$\)/ contains='.s:ledgerAccounts_contains.' contained'
execute 'syntax match ledgerAmount '.
\ '/'.s:oe.'\S'.s:lb1.'\%( \|\t\)\s*\zs\%([^();[:space:]]\|\s\+[^();[:space:]]\)\+/ contains='.s:ledgerAmounts_contains.' contained'
execute 'syntax match ledgerValueExpression '.
\ '/'.s:oe.'\S'.s:lb1.'\%( \|\t\)\s*\zs(\%([^;[:space:]]\|\s\+[^;[:space:]]\)\+)/ contains='.s:ledgerAmounts_contains.' contained'
syn region ledgerPreDeclaration start=/^\(account\|payee\|commodity\|tag\)/ skip=/^\s/ end=/^/
syntax region ledgerPreDeclaration start=/^\(account\|payee\|commodity\|tag\)/ skip=/^\s/ end=/^/
\ keepend transparent
\ contains=ledgerPreDeclarationType,ledgerPreDeclarationName,ledgerPreDeclarationDirective
syn match ledgerPreDeclarationType /^\(account\|payee\|commodity\|tag\)/ contained
syn match ledgerPreDeclarationName /^\S\+\s\+\zs.*/ contained
syn match ledgerPreDeclarationDirective /^\s\+\zs\S\+/ contained
syntax match ledgerPreDeclarationType /^\(account\|payee\|commodity\|tag\)/ contained
syntax match ledgerPreDeclarationName /^\S\+\s\+\zs.*/ contained
syntax match ledgerPreDeclarationDirective /^\s\+\zs\S\+/ contained
syn match ledgerDirective
syntax match ledgerDirective
\ /^\%(alias\|assert\|bucket\|capture\|check\|define\|expr\|fixed\|include\|year\)\s/
syn match ledgerOneCharDirective /^\%(P\|A\|Y\|N\|D\|C\)\s/
syntax match ledgerOneCharDirective /^\%(P\|A\|Y\|N\|D\|C\)\s/
syn region ledgerBlockComment start=/^comment/ end=/^end comment/
syn region ledgerBlockTest start=/^test/ end=/^end test/
syn match ledgerComment /^[;|*#].*$/
" comments at eol must be preceded by at least 2 spaces / 1 tab
syn region ledgerMetadata start=/\%( \|\t\|^\s\+\);/ skip=/^\s\+;/ end=/^/
\ keepend contained contains=ledgerTags,ledgerValueTag,ledgerTypedTag
exe 'syn match ledgerTags '.
\ '/'.s:oe.'\%(\%(;\s*\|^tag\s\+\)\)\@<='.
\ ':[^:[:space:]][^:]*\%(::\?[^:[:space:]][^:]*\)*:\s*$/ '.
\ 'contained contains=ledgerTag'
syn match ledgerTag /:\zs[^:]\+\ze:/ contained
exe 'syn match ledgerValueTag '.
\ '/'.s:oe.'\%(\%(;\|^tag\)[^:]\+\)\@<=[^:]\+:\ze.\+$/ contained'
exe 'syn match ledgerTypedTag '.
\ '/'.s:oe.'\%(\%(;\|^tag\)[^:]\+\)\@<=[^:]\+::\ze.\+$/ contained'
syntax region ledgerBlockComment start=/^comment/ end=/^end comment/
syntax region ledgerBlockTest start=/^test/ end=/^end test/
execute 'syntax match ledgerComment /^['.s:line_comment_chars.'].*$/'
syn region ledgerApply
" Allow manual fold markers in comments
execute 'syntax region ledgerManualFold start=/^['.s:line_comment_chars.']\s*{{{/ end=/^['.s:line_comment_chars.']\s*}}}/ fold transparent'
" Tags (metadata) are handled a bit differently in ledger-cli vs. hledger even
" though they both nested in comments the same way.
if b:ledger_is_hledger
syntax region ledgerTransactionMetadata start=/;/ end=/^/
\ keepend contained contains=ledgerTags
syntax region ledgerPostingMetadata start=/;/ end=/^/
\ keepend contained contains=ledgerTags
else
syntax region ledgerTransactionMetadata start=/\%(\s\s\|\t\|^\s\+\);/ end=/^/
\ keepend contained contains=ledgerTags,ledgerValueTag,ledgerTypedTag
syntax region ledgerPostingMetadata start=/;/ end=/^/
\ keepend contained contains=ledgerTags,ledgerValueTag,ledgerTypedTag
endif
" https://hledger.org/tags-tutorial.html
" https://www.ledger-cli.org/3.0/doc/ledger3.html#Metadata
if b:ledger_is_hledger
syntax match ledgerTags /\v[[:alnum:]_-]+:[^,;]*/
\ contained contains=ledgerTag
syntax match ledgerTag /\v[[:alnum:]_-]+/ contained nextgroup=ledgerTagDef
syntax match ledgerTagDef ":" contained nextgroup=ledgerTagValue,ledgerTagSep
syntax match ledgerTagValue /\v[^,;]+/ contained nextgroup=ledgerTagSep
syntax match ledgerTagSep /,/ contained
else
execute 'syntax match ledgerTags '.
\ '/'.s:oe.'\%(\%(;\s*\|^tag\s\+\)\)\@<='.
\ ':[^:[:space:]][^:]*\%(::\?[^:[:space:]][^:]*\)*:\s*$/ '.
\ 'contained contains=ledgerTag'
syntax match ledgerTag /:\zs[^:]\+\ze:/ contained
execute 'syntax match ledgerValueTag '.
\ '/'.s:oe.'\%(\%(;\|^tag\)[^:]\+\)\@<=[^:]\+:\ze.\+$/ contained'
execute 'syntax match ledgerTypedTag '.
\ '/'.s:oe.'\%(\%(;\|^tag\)[^:]\+\)\@<=[^:]\+::\ze.\+$/ contained'
endif
syntax region ledgerApply
\ matchgroup=ledgerStartApply start=/^apply\>/
\ matchgroup=ledgerEndApply end=/^end\s\+apply\>/
\ contains=ledgerApplyHead,ledgerApply,ledgerTransaction,ledgerComment
exe 'syn match ledgerApplyHead '.
\ '/'.s:oe.'\%(^apply\s\+\)\@<=\S.*$/ contained'
execute 'syntax match ledgerApplyHead '.
\ '/'.s:oe.'\%(^apply\s\+\)\@<=\S.*$/ contained'
syntax keyword ledgerTodo FIXME TODO
\ contained containedin=ledgerComment,ledgerTransaction,ledgerTransactionMetadata,ledgerPostingMetadata
highlight default link ledgerComment Comment
highlight default link ledgerBlockComment Comment
highlight default link ledgerBlockTest Comment
highlight default link ledgerTransactionDate Constant
highlight default link ledgerTransactionExpression Statement
highlight default link ledgerMetadata Tag
highlight default link ledgerTransactionMetadata Tag
highlight default link ledgerPostingMetadata Tag
highlight default link ledgerTypedTag Keyword
highlight default link ledgerValueTag Type
highlight default link ledgerTag Type
highlight default link ledgerTagValue Label
highlight default link ledgerTagDef Delimiter
highlight default link ledgerTagSep Delimiter
highlight default link ledgerStartApply Tag
highlight default link ledgerEndApply Tag
highlight default link ledgerApplyHead Type
highlight default link ledgerAccount Identifier
highlight default link ledgerAmount Number
highlight default link ledgerValueExpression Function
highlight default link ledgerPreDeclarationType Type
highlight default link ledgerPreDeclarationName Identifier
highlight default link ledgerPreDeclarationDirective Type
highlight default link ledgerDirective Type
highlight default link ledgerOneCharDirective Type
highlight default link ledgerTodo Todo
" syncinc is easy: search for the first transaction.
syn sync clear
syn sync match ledgerSync grouphere ledgerTransaction "^[[:digit:]~=]"
let b:current_syntax = "ledger"
syntax sync clear
syntax sync match ledgerSync grouphere ledgerTransaction "^[[:digit:]~=]"
let b:current_syntax = b:ledger_is_hledger ? 'hledger' : 'ledger'

View File

@@ -0,0 +1,29 @@
; tests transactions for folds
2025-01-01 test simple fold, no assertion, should read 100.10
io:income
assets:bank £ 100.10
2025-01-01 test positive assertion. should read 100.20
io:income
assets:bank £ 100.20 = £ 200.10
2025-01-01 no assertion, negative txn, should read -13
io:income
assets:bank £ -13
2025-01-01 test negative assertion. should read -400
io:income
assets:bank £ -400 = £ -199.7
2025-01-01 as above, sign and currency swapped. should read -400
io:income
assets:bank £ -400 = - £199.7
2025-01-01 test positive assert. should be 10
io:income
assets:bank £ 10 = £ +12
2025-01-01 test positive assert 2. should be 9
io:income
assets:bank £ 9 = + £ 12