chore: make glint release-ready for v0.1.0 (Homebrew via custard)
03fcb12b06b2431b5366148a5f11bf2e316afe7a
humdrum <me@humdrum.me> · 2026-06-28 16:50
parent 0a0d5ea0
chore: make glint release-ready for v0.1.0 (Homebrew via custard) - config: vault defaults to $GLINT_VAULT, else cwd (was hardcoded ~/Humdrum); a config-file vault_dir still overrides. Removes the only personal path that shipped in the binary. - version: add a version var (forge formula injects -X main.version) and `glint version` / --version / -v. - .custard.yaml: CI (golangci-lint, vet, test) + brew release config. - LICENSE (AGPL-3.0), rewritten README (install/usage/keys/config/themes), CHANGELOG with the v0.1.0 entry. - .golangci.yml + fixes: drop ineffectual assignment in preview, simplify the pending-discard guard; lint is clean. - move docs/superpowers planning docs out of the repo (into the vault) and genericize a test fixture path. No machine paths or identity ship in the repo. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
18 files changed
.custard.yaml +10 −0
@@ -0,0 +1,10 @@
+# custard release config — glint is a Go CLI distributed via the Homebrew tap.
+ci:
+ - golangci-lint run
+ - go vet ./...
+ - go test ./...
+brew:
+ enabled: true
+ package: "." # main is at the repo root
+ source: bookmark # jj-native: release ref = release/vX.Y.Z bookmark
+ bookmark_prefix: "release/"
.golangci.yml +8 −0
@@ -0,0 +1,8 @@
+version: "2"
+linters:
+ exclusions:
+ rules:
+ # Test setup commonly ignores errors from fixtures (os.WriteFile, Load, …).
+ - path: _test\.go
+ linters:
+ - errcheck
CHANGELOG.md +44 −0
@@ -0,0 +1,44 @@
+# Changelog
+
+All notable changes to glint are documented here. Format follows
+[Keep a Changelog](https://keepachangelog.com/); versions follow
+[Semantic Versioning](https://semver.org/).
+
+## [0.1.0] — 2026-06-28
+
+First public release.
+
+### Editor
+- Modeless markdown editor with live styling: headings, emphasis, code,
+ links, wikilinks, list markers, and blockquotes colored as you type, with the
+ raw markup always visible.
+- YAML frontmatter syntax highlighting (keys, values, list markers, comments).
+- iA-Writer-style writing canvas: a centered, percentage-width text column with
+ margins and a top pad; long paragraphs soft-wrap word-aware (display only — the
+ file round-trips exactly).
+- Visual-row cursor and scrolling: Up/Down move by visual line with a goal
+ column; Left/Right and Home/End stay logical.
+
+### Themes
+- Three palettes — flexoki-light, flexoki-dark, charm — every span explicitly
+ colored (readable on light and dark terminals) and the full canvas background
+ painted to the theme.
+- `theme = auto` detects macOS light/dark; `Ctrl+T` cycles themes live; the read
+ preview stays in sync.
+
+### Navigation & files
+- Glamour read preview (`Ctrl+P`), sharing the canvas column.
+- Fuzzy file picker (`Ctrl+F`) sorted by modified date with today's daily note
+ floated to the top and a live preview pane.
+- Today's daily note (`Ctrl+D`), created on demand.
+- `glint new` starts a fresh document from anywhere; `glint new <name>` creates a
+ note under the inbox; `Ctrl+N` starts a new doc in the editor or a note from
+ the query in the picker. Unnamed buffers get a save-as prompt on `Ctrl+S`.
+- Open-while-dirty and quit are confirm-then-discard.
+
+### Configuration
+- `~/.config/glint/config.toml`: `vault_dir` (default `$GLINT_VAULT`, else the
+ current directory), `inbox_dir`, `daily_subdir`, `daily_format`, `theme`,
+ `glamour_style`.
+
+[0.1.0]: https://codex.humdrum.me/git/glint
LICENSE +661 −0
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ 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
+them 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey 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;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ 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.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+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.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ 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
+state 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 Affero General Public License as published by
+ the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
README.md +81 −1
@@ -1,3 +1,83 @@
# glint
-Pretty terminal markdown editor (Go + Bubbletea + Glamour). Obsidian-vault companion.
+A modeless terminal markdown editor with live styling — a [Bubble Tea][bubbletea]
+TUI built for a notes vault. Type in a centered iA-Writer-style writing canvas
+with soft-wrapping and live markdown coloring, flip to a [Glamour][glamour] read
+preview, fuzzy-find notes with a live preview pane, and theme it to match your
+terminal (Flexoki light/dark + charm). Open any file, jump to today's daily
+note, or start a fresh document from anywhere.
+
+## Install
+
+```sh
+brew tap humdrum/tap https://codex.humdrum.me/git/homebrew-tap.git
+brew trust humdrum/tap # Homebrew gates third-party taps
+brew install glint
+```
+
+Upgrade later:
+
+```sh
+brew update && brew upgrade glint
+```
+
+## Usage
+
+```bash
+glint # open the fuzzy picker over your vault
+glint notes.md # open a file
+glint --daily # open (and create) today's daily note
+glint new # start a blank scratch document
+glint new ideas # create and open <inbox>/ideas.md
+glint --version # print version
+```
+
+### Keys
+
+| Key | Action |
+| --- | --- |
+| type / arrows / `Enter` / `Backspace` / `Del` | edit and move (Up/Down move by visual line) |
+| `Ctrl+S` | save (an unnamed buffer prompts for a name → inbox) |
+| `Ctrl+P` | toggle the Glamour read preview |
+| `Ctrl+F` | fuzzy file picker (with live preview) |
+| `Ctrl+D` | today's daily note |
+| `Ctrl+N` | new document (in the editor) / new note from the query (in the picker) |
+| `Ctrl+T` | cycle theme (flexoki-light → flexoki-dark → charm) |
+| `Ctrl+Q` | quit (press twice if there are unsaved changes) |
+| `Esc` | back to the editor |
+
+## Configuration
+
+glint reads `~/.config/glint/config.toml` (all keys optional):
+
+```toml
+vault_dir = "" # notes root; default: $GLINT_VAULT, else the current directory
+inbox_dir = "" # where `glint new` / save-as land; "" = vault root, relative = under vault
+daily_subdir = "Daily" # daily notes live in <vault>/<daily_subdir>/
+daily_format = "2006-01-02" # Go time layout for daily-note filenames
+theme = "auto" # auto | flexoki-light | flexoki-dark | charm (auto detects macOS appearance)
+glamour_style = "" # override the preview style; "" follows the theme
+```
+
+The vault resolves as `vault_dir` (config) → `$GLINT_VAULT` → the current working
+directory, so `glint` works in whatever folder you launch it from.
+
+## Themes
+
+Three palettes, every span explicitly colored so text stays readable on light
+and dark terminals: **flexoki-light**, **flexoki-dark**, and **charm**. `auto`
+picks light or dark from the macOS system appearance; `Ctrl+T` cycles live. The
+read preview and the whole canvas background follow the active theme.
+
+## License
+
+glint — Copyright (C) 2026 humdrum-tiv.
+
+Free software under the [GNU Affero General Public License v3.0](LICENSE) (or, at
+your option, any later version). You may use, study, share, and modify it; any
+distributed derivative — **or modified version offered to users over a network** —
+must also be AGPL-licensed with source available. It comes with **no warranty**.
+See [LICENSE](LICENSE) for the full terms.
+
+[bubbletea]: https://github.com/charmbracelet/bubbletea
+[glamour]: https://github.com/charmbracelet/glamour
docs/superpowers/2026-06-28-glint-handoff.md +0 −69
@@ -1,69 +0,0 @@
-# glint — Handoff (2026-06-28)
-
-Pick-up doc for a fresh conversation. Everything needed to execute the two pending increments.
-
-## Where things stand
-
-- **Repo:** `~/Developer/Home/glint` — Go 1.26.4, module path `glint`, packages under `internal/`.
-- **v1 is DONE and merged to `main`** (modeless terminal markdown editor: config, styling scanner, editor buffer/ops/view, app routing+save/load+quit-confirm, glamour preview, fuzzy picker + daily note, entrypoint). `go vet/build/test ./...` clean. v1 was built via subagent-driven-development; its final whole-branch review caught and fixed 3 cross-package bugs (open-while-dirty data loss → confirm-then-discard, picker sizing, status-bar layout).
-- **VCS:** the repo is now **jj-colocated** (`.jj` + `.git`). `main` bookmark is at the v1.1 design-spec commit. A git/jj remote **`soft`** → `soft:glint` (soft-serve at `kortum@codex.humdrum.me:23231`) is configured but **nothing has been pushed yet**.
-- **Dependency policy (decided by the user):** use the **newest** versions Go's resolver selects; do **not** pin to specific numbers and do not flag version drift as a defect. (The plan's original exact pins were abandoned because glamour v1.0.0 transitively requires a lipgloss prerelease above v1.1.0 — the two could not both be pinned.)
-
-## Two increments to build, in order
-
-Build **increment 1 fully (merge), then increment 2.** Both modify `editor` rendering; sequencing avoids churn. Increment 2's editor work assumes increment 1's themed editor (`editor` consumes `theme.Theme`, app holds `a.theme`).
-
-### Increment 1 — Themes + Picker + YAML (v1.1)
-- Spec: `docs/superpowers/specs/2026-06-28-glint-theme-picker-design.md`
-- Plan: `docs/superpowers/plans/2026-06-28-glint-theme-picker.md` (7 tasks)
-- Delivers: `internal/theme` package (Flexoki light/dark + charm.land, concrete hexes); macOS light/dark auto-detect; `theme=auto` config key; `Ctrl+T` live theme cycle; glamour preview synced to theme; picker sorts by modified-date with today's daily floated on top; live glamour **preview pane** in the picker; `Ctrl+N` new-note from the query; YAML frontmatter syntax-highlighting. Full-text picker search is explicitly deferred.
-
-### Increment 2 — Writing canvas (v1.2)
-- Spec: `docs/superpowers/specs/2026-06-28-glint-writing-canvas-design.md`
-- Plan: `docs/superpowers/plans/2026-06-28-glint-writing-canvas.md` (3 tasks)
-- Delivers: iA Writer–style canvas — centered, percentage-width text column (`clamp(round(W×0.65),24,100)`) with left/right margins + a top pad; text left-aligned inside it; long paragraphs **soft-wrap** word-aware at the column edge; editor cursor/scroll become **visual-row** aware (Up/Down move by visual line with a goal column; Left/Right & Home/End stay logical); the `Ctrl+R` preview shares the column. Picker keeps its full-width split. Cursor is a themed cell (a TUI can't draw iA's thin bar).
-
-## How to execute
-
-Use the **superpowers:subagent-driven-development** skill (same flow that built v1):
-- Fresh implementer subagent per task; two-stage review (spec compliance + code quality) after each; a broad whole-branch review at the end of each increment.
-- **Models:** the plans contain complete code, so implementers are transcription work → use **haiku**. Reviewers → **sonnet**. Final whole-branch review → **opus**.
-- The plans are TDD with exact code and commands; follow them step-by-step. Don't improvise designs the plans already specify.
-- **Ledger:** progress is tracked in `.superpowers/sdd/progress.md` (git-ignored). It already records v1's tasks and carried-forward Minor findings — read it at start; resume at the first task not marked complete; append a line per completed task. The skill's scripts live at `~/.claude/plugins/cache/claude-plugins-official/superpowers/6.0.3/skills/subagent-driven-development/scripts/` (`task-brief`, `review-package`).
-
-### jj note (important)
-The repo is jj-colocated. The plan steps say `git add` / `git commit` per task — these **work** in a colocated repo (jj auto-imports git operations on the next `jj` command), so you may run them as written. But for VCS *navigation* (status, log, branches, push) prefer **jj** (`jj st`, `jj log`, `jj bookmark`, `jj git push`) and load the **jj-guide** skill before any jj mutation. Recommended shape: do each increment's work on its own jj bookmark (or a git branch), let the per-task `git commit`s land, then at finish use jj to advance `main` and (optionally) `jj git push -b main` to `soft`. After any `git commit`, a quick `jj log` confirms the import.
-
-## Invariants (do not break — reviewers must check)
-
-1. **Explicit foreground:** every styled span, in every theme (light included), gets an explicit theme foreground — never the terminal default. This is the root-cause fix for unreadable text on light terminals.
-2. **Markup-visible:** the editor scanner never adds/removes characters; concatenated span texts equal the raw line; raw markup (`**`, `##`, `[[`, backticks) stays visible. Soft-wrapping (increment 2) is display-only: the buffer is untouched and `Bytes()` round-trips exactly.
-
-## Verify + smoke
-
-Per task and at the end: `go vet ./...`, `go build ./...`, `go test ./...` all clean.
-
-Manual smoke needs a **real terminal** (the editor is an AltScreen TUI; it can't be driven from a non-TTY harness — the agent that built v1 confirmed build/flag-parse/error-path/first-frame render but could not drive keys). Have the user run:
-```bash
-go run . README.md # editor; Ctrl+T themes, Ctrl+R preview, Ctrl+P picker, Ctrl+D daily, Ctrl+N new note
-go run . # bare → picker (mtime order, today on top, preview pane)
-```
-Expected after both increments: readable in a light terminal; Ctrl+T cycles flexoki-light → flexoki-dark → charm; YAML frontmatter shows colored keys/values with muted `---`; picker is newest-first with today's daily on top and a glamour preview pane; text sits in a centered column with margins and long paragraphs soft-wrap.
-
-## Tracking
-
-Update `~/Humdrum/Claude/Projects/glint.md` at checkpoints (delegate doc writes to a Haiku subagent per the user's CLAUDE.md). Capture any new bugs/ideas as Backlog.md tasks in the repo.
-
-## Keybinds (current + planned)
-
-| Key | Action | Status |
-|---|---|---|
-| type / arrows / Enter / Backspace / Del | edit / move | v1 |
-| `Ctrl+S` | save | v1 |
-| `Ctrl+R` | toggle glamour preview | v1 |
-| `Ctrl+P` | fuzzy picker (confirm-then-discard if dirty) | v1 |
-| `Ctrl+D` | today's daily note (confirm-then-discard if dirty) | v1 |
-| `Esc` | back to editor | v1 |
-| `Ctrl+Q` | quit (twice if dirty) | v1 |
-| `Ctrl+T` | cycle theme | v1.1 |
-| `Ctrl+N` | new note from picker query | v1.1 |
docs/superpowers/plans/2026-06-27-glint-editor.md +0 −2409
@@ -1,2418 +0,0 @@
-# glint Editor (v1) Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Build a modeless terminal markdown editor with live inline styling (markup stays visible), a glamour read-preview, a fuzzy file picker, and a daily-note jump.
-
-**Architecture:** Bubbletea MVU. A top-level `app` model holds a `mode` enum (Editor | Picker | Preview) and routes messages to the active sub-model. The `editor` package is a self-contained text buffer plus a hand-rolled, line-oriented markdown styling scanner that emits Lipgloss-styled spans char-for-char aligned with the raw text (no concealment). `preview` wraps Glamour; `picker` walks a directory and fuzzy-filters; `config` loads TOML.
-
-**Tech Stack:** Go 1.26, Bubbletea v1.3.10, Bubbles v1.0.0 (viewport, textinput), Lipgloss v1.1.0, Glamour v1.0.0, BurntSushi/toml v1.6.0.
-
-## Global Constraints
-
-- Module path: `glint`. Internal packages import as `glint/internal/<pkg>`.
-- Go version floor: `go 1.26`.
-- Pinned dependency versions (exact): bubbletea `v1.3.10`, bubbles `v1.0.0`, lipgloss `v1.1.0`, glamour `v1.0.0`, BurntSushi/toml `v1.6.0`.
-- **Styling invariant:** every emitted span — including plain prose and empty lines — gets an explicit `Foreground` from the theme. Never `lipgloss.Style{}` / terminal default. This is the root-cause fix for the ekphos light-terminal bug.
-- **Markup-visible invariant:** the styling scanner never inserts or deletes characters. The concatenation of a line's span texts equals the raw line exactly.
-- Modeless editing only. No vim modes.
-- Config keys (TOML, `~/.config/glint/config.toml`): `vault_dir`, `daily_subdir`, `daily_format` (Go reference-time layout), `glamour_style`.
-- Config defaults: `vault_dir = "<home>/Humdrum"`, `daily_subdir = "Daily"`, `daily_format = "2006-01-02"`, `glamour_style = "dark"`.
-- Keybinds: `Ctrl+S` save, `Ctrl+P` picker, `Ctrl+D` daily, `Ctrl+R` preview toggle, `Esc` back to editor, `Ctrl+Q` quit (confirm if dirty).
-
----
-
-## File Structure
-
-```
-glint/
- go.mod
- main.go entrypoint: flags, config load, build app, run program
- internal/
- config/
- config.go Config struct, Load, Default, DailyPath
- config_test.go
- editor/
- theme.go Theme struct + DefaultDarkTheme
- span.go Span type + render helpers (with/without cursor)
- scanner.go blockState, ScanLines, scanLine, scanInline, matchToken
- scanner_test.go
- editor.go Editor model: buffer, cursor, scroll, dirty, ops, View
- editor_test.go
- preview/
- preview.go Glamour render -> viewport wrapper
- preview_test.go
- picker/
- picker.go dir walk, fuzzy match, textinput query, selection
- picker_test.go
- app/
- app.go top model: mode enum, routing, status bar, save/load
- app_test.go
-```
-
-Each `internal/` package has one responsibility and is testable without a running terminal. `editor` knows nothing about files or the vault (the app wires save/load). `config`, the scanner, the editor ops, and the fuzzy matcher are all pure and carry the high-value unit tests.
-
----
-
-## Task 1: Project scaffold + config package
-
-**Files:**
-- Create: `go.mod` (via `go mod init`)
-- Create: `internal/config/config.go`
-- Test: `internal/config/config_test.go`
-
-**Interfaces:**
-- Consumes: nothing (first task).
-- Produces:
- - `config.Config` struct with fields `VaultDir, DailySubdir, DailyFormat, GlamourStyle string`.
- - `config.Default() Config`
- - `config.Load() (Config, error)` — reads `~/.config/glint/config.toml`, overlays onto defaults; absent file → defaults + nil error; malformed → defaults + non-nil error.
- - `config.loadFromFile(path string) (Config, error)` — unexported, testable core of `Load`.
- - `func (c Config) DailyPath(t time.Time) string`
-
-- [ ] **Step 1: Initialize the module and fetch pinned dependencies**
-
-Run:
-```bash
-cd /Users/kortum/Developer/Home/glint
-go mod init glint
-go get github.com/charmbracelet/bubbletea@v1.3.10
-go get github.com/charmbracelet/bubbles@v1.0.0
-go get github.com/charmbracelet/lipgloss@v1.1.0
-go get github.com/charmbracelet/glamour@v1.0.0
-go get github.com/BurntSushi/toml@v1.6.0
-```
-Expected: `go.mod` created with `module glint`, `go 1.26`, and the five `require` lines.
-
-- [ ] **Step 2: Write the failing test**
-
-Create `internal/config/config_test.go`:
-```go
-package config
-
-import (
- "os"
- "path/filepath"
- "testing"
- "time"
-)
-
-func TestDefaultHasSaneValues(t *testing.T) {
- d := Default()
- if d.DailySubdir != "Daily" {
- t.Errorf("DailySubdir = %q, want Daily", d.DailySubdir)
- }
- if d.DailyFormat != "2006-01-02" {
- t.Errorf("DailyFormat = %q, want 2006-01-02", d.DailyFormat)
- }
- if d.GlamourStyle != "dark" {
- t.Errorf("GlamourStyle = %q, want dark", d.GlamourStyle)
- }
- if d.VaultDir == "" {
- t.Error("VaultDir should not be empty")
- }
-}
-
-func TestLoadFromFileMissingReturnsDefaults(t *testing.T) {
- cfg, err := loadFromFile(filepath.Join(t.TempDir(), "nope.toml"))
- if err != nil {
- t.Fatalf("missing file should not error, got %v", err)
- }
- if cfg.DailyFormat != "2006-01-02" {
- t.Errorf("DailyFormat = %q, want default", cfg.DailyFormat)
- }
-}
-
-func TestLoadFromFileOverlays(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "config.toml")
- body := `vault_dir = "/tmp/vault"
-daily_subdir = "journal"
-daily_format = "20060102"
-`
- if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
- t.Fatal(err)
- }
- cfg, err := loadFromFile(path)
- if err != nil {
- t.Fatal(err)
- }
- if cfg.VaultDir != "/tmp/vault" {
- t.Errorf("VaultDir = %q", cfg.VaultDir)
- }
- if cfg.DailySubdir != "journal" {
- t.Errorf("DailySubdir = %q", cfg.DailySubdir)
- }
- if cfg.DailyFormat != "20060102" {
- t.Errorf("DailyFormat = %q", cfg.DailyFormat)
- }
- // unset key keeps default
- if cfg.GlamourStyle != "dark" {
- t.Errorf("GlamourStyle = %q, want default dark", cfg.GlamourStyle)
- }
-}
-
-func TestLoadFromFileMalformedErrors(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "bad.toml")
- if err := os.WriteFile(path, []byte("vault_dir = = ="), 0o644); err != nil {
- t.Fatal(err)
- }
- if _, err := loadFromFile(path); err == nil {
- t.Error("malformed config should return an error")
- }
-}
-
-func TestDailyPath(t *testing.T) {
- c := Config{VaultDir: "/v", DailySubdir: "Daily", DailyFormat: "2006-01-02"}
- got := c.DailyPath(time.Date(2026, 6, 27, 0, 0, 0, 0, time.UTC))
- want := filepath.Join("/v", "Daily", "2026-06-27.md")
- if got != want {
- t.Errorf("DailyPath = %q, want %q", got, want)
- }
-}
-```
-
-- [ ] **Step 3: Run the test to verify it fails**
-
-Run: `go test ./internal/config/`
-Expected: FAIL — `undefined: Default`, `undefined: loadFromFile`, `undefined: Config`.
-
-- [ ] **Step 4: Write the implementation**
-
-Create `internal/config/config.go`:
-```go
-// Package config loads glint's TOML configuration, falling back to defaults.
-package config
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "time"
-
- "github.com/BurntSushi/toml"
-)
-
-// Config holds the user-tunable settings glint reads at startup.
-type Config struct {
- VaultDir string `toml:"vault_dir"`
- DailySubdir string `toml:"daily_subdir"`
- DailyFormat string `toml:"daily_format"`
- GlamourStyle string `toml:"glamour_style"`
-}
-
-// Default returns the built-in configuration used when no file is present.
-func Default() Config {
- home, _ := os.UserHomeDir()
- return Config{
- VaultDir: filepath.Join(home, "Humdrum"),
- DailySubdir: "Daily",
- DailyFormat: "2006-01-02",
- GlamourStyle: "dark",
- }
-}
-
-// Load reads ~/.config/glint/config.toml and overlays it onto the defaults.
-func Load() (Config, error) {
- home, err := os.UserHomeDir()
- if err != nil {
- return Default(), nil
- }
- return loadFromFile(filepath.Join(home, ".config", "glint", "config.toml"))
-}
-
-// loadFromFile is the testable core of Load. A missing file yields the
-// defaults with no error; a malformed file yields the defaults plus an error.
-func loadFromFile(path string) (Config, error) {
- cfg := Default()
- data, err := os.ReadFile(path)
- if err != nil {
- return cfg, nil // absent config is fine
- }
- var fileCfg Config
- if _, err := toml.Decode(string(data), &fileCfg); err != nil {
- return cfg, fmt.Errorf("parse %s: %w", path, err)
- }
- if fileCfg.VaultDir != "" {
- cfg.VaultDir = fileCfg.VaultDir
- }
- if fileCfg.DailySubdir != "" {
- cfg.DailySubdir = fileCfg.DailySubdir
- }
- if fileCfg.DailyFormat != "" {
- cfg.DailyFormat = fileCfg.DailyFormat
- }
- if fileCfg.GlamourStyle != "" {
- cfg.GlamourStyle = fileCfg.GlamourStyle
- }
- return cfg, nil
-}
-
-// DailyPath builds the absolute path to the daily note for time t.
-func (c Config) DailyPath(t time.Time) string {
- return filepath.Join(c.VaultDir, c.DailySubdir, t.Format(c.DailyFormat)+".md")
-}
-```
-
-- [ ] **Step 5: Run the test to verify it passes**
-
-Run: `go test ./internal/config/`
-Expected: PASS (all five tests).
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add go.mod go.sum internal/config/
-git commit -m "feat: project scaffold + config package"
-```
-
----
-
-## Task 2: Theme + styling scanner
-
-**Files:**
-- Create: `internal/editor/theme.go`
-- Create: `internal/editor/span.go`
-- Create: `internal/editor/scanner.go`
-- Test: `internal/editor/scanner_test.go`
-
-**Interfaces:**
-- Consumes: nothing from earlier tasks.
-- Produces:
- - `editor.Theme` struct with `lipgloss.Color` fields: `Text, Heading, Code, Link, Wikilink, ListMarker, Blockquote, Accent`.
- - `editor.DefaultDarkTheme() Theme`
- - `editor.Span` struct `{ Text string; Style lipgloss.Style }`
- - `editor.renderSpans(spans []Span) string`
- - `editor.renderSpansCursor(spans []Span, col int, cursorStyle lipgloss.Style) string`
- - `editor.ScanLines(lines []string, th Theme) [][]Span` — one span slice per input line, char-for-char aligned.
-
-- [ ] **Step 1: Write the failing test for the theme and span renderers**
-
-Create `internal/editor/scanner_test.go`:
-```go
-package editor
-
-import (
- "testing"
-
- "github.com/charmbracelet/lipgloss"
-)
-
-// spanText concatenates the raw text of a line's spans. It must equal the
-// original raw line exactly (markup-visible invariant).
-func spanText(spans []Span) string {
- s := ""
- for _, sp := range spans {
- s += sp.Text
- }
- return s
-}
-
-func TestDefaultThemeAllColorsSet(t *testing.T) {
- th := DefaultDarkTheme()
- colors := []lipgloss.Color{
- th.Text, th.Heading, th.Code, th.Link,
- th.Wikilink, th.ListMarker, th.Blockquote, th.Accent,
- }
- for i, c := range colors {
- if c == "" {
- t.Errorf("theme color %d is empty", i)
- }
- }
-}
-
-func TestRenderSpansPreservesText(t *testing.T) {
- spans := []Span{
- {Text: "ab", Style: lipgloss.NewStyle()},
- {Text: "cd", Style: lipgloss.NewStyle()},
- }
- // rendering may add ANSI, but stripped content is checked elsewhere;
- // here we only assert it does not panic and is non-empty.
- if renderSpans(spans) == "" {
- t.Error("renderSpans returned empty for non-empty spans")
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/editor/`
-Expected: FAIL — `undefined: Span`, `undefined: DefaultDarkTheme`, `undefined: renderSpans`.
-
-- [ ] **Step 3: Implement the theme**
-
-Create `internal/editor/theme.go`:
-```go
-package editor
-
-import "github.com/charmbracelet/lipgloss"
-
-// Theme holds the explicit foreground colors used by the styling scanner.
-// Every span gets one of these — none ever defaults to the terminal foreground.
-type Theme struct {
- Text lipgloss.Color
- Heading lipgloss.Color
- Code lipgloss.Color
- Link lipgloss.Color
- Wikilink lipgloss.Color
- ListMarker lipgloss.Color
- Blockquote lipgloss.Color
- Accent lipgloss.Color
-}
-
-// DefaultDarkTheme is a Tokyo-Night-ish palette that reads on dark terminals.
-func DefaultDarkTheme() Theme {
- return Theme{
- Text: lipgloss.Color("#c0caf5"),
- Heading: lipgloss.Color("#7aa2f7"),
- Code: lipgloss.Color("#9ece6a"),
- Link: lipgloss.Color("#7dcfff"),
- Wikilink: lipgloss.Color("#bb9af7"),
- ListMarker: lipgloss.Color("#bb9af7"),
- Blockquote: lipgloss.Color("#565f89"),
- Accent: lipgloss.Color("#e0af68"),
- }
-}
-```
-
-- [ ] **Step 4: Implement the span type and renderers**
-
-Create `internal/editor/span.go`:
-```go
-package editor
-
-import (
- "strings"
-
- "github.com/charmbracelet/lipgloss"
-)
-
-// Span is a run of text with a single Lipgloss style.
-type Span struct {
- Text string
- Style lipgloss.Style
-}
-
-// renderSpans concatenates styled spans into a single string.
-func renderSpans(spans []Span) string {
- var b strings.Builder
- for _, s := range spans {
- b.WriteString(s.Style.Render(s.Text))
- }
- return b.String()
-}
-
-// renderSpansCursor renders spans rune-by-rune, drawing the cursor cell at the
-// given rune column with cursorStyle. A cursor at or past the end of the line
-// is drawn as a styled space.
-func renderSpansCursor(spans []Span, col int, cursorStyle lipgloss.Style) string {
- var b strings.Builder
- idx := 0
- for _, s := range spans {
- for _, r := range s.Text {
- if idx == col {
- b.WriteString(cursorStyle.Render(string(r)))
- } else {
- b.WriteString(s.Style.Render(string(r)))
- }
- idx++
- }
- }
- if col >= idx {
- b.WriteString(cursorStyle.Render(" "))
- }
- return b.String()
-}
-```
-
-- [ ] **Step 5: Run to verify theme/renderer tests pass**
-
-Run: `go test ./internal/editor/ -run 'TestDefaultTheme|TestRenderSpans'`
-Expected: PASS.
-
-- [ ] **Step 6: Write the failing test for the scanner**
-
-Append to `internal/editor/scanner_test.go`:
-```go
-func TestScanPlainTextGetsExplicitForeground(t *testing.T) {
- th := DefaultDarkTheme()
- out := ScanLines([]string{"hello world"}, th)
- if len(out) != 1 || len(out[0]) == 0 {
- t.Fatalf("expected spans for one line, got %v", out)
- }
- for _, sp := range out[0] {
- // A style with no foreground returns "" from GetForeground().
- if sp.Style.GetForeground() == lipgloss.Color("") {
- t.Errorf("plain span %q has no explicit foreground", sp.Text)
- }
- }
-}
-
-func TestScanPreservesRawTextAcrossConstructs(t *testing.T) {
- th := DefaultDarkTheme()
- lines := []string{
- "# Heading",
- "plain **bold** and *italic* and `code`",
- "- a list item with a [link](http://x) and [[wikilink]]",
- "> a quote",
- "```",
- "raw **not bold** here",
- "```",
- "---",
- }
- out := ScanLines(lines, th)
- for i, raw := range lines {
- if got := spanText(out[i]); got != raw {
- t.Errorf("line %d: span text %q != raw %q", i, got, raw)
- }
- }
-}
-
-func TestScanFencedCodeSuppressesInline(t *testing.T) {
- th := DefaultDarkTheme()
- lines := []string{"```", "**x**", "```"}
- out := ScanLines(lines, th)
- // The fence body line should be a single code-colored span, not split
- // into bold spans.
- if len(out[1]) != 1 {
- t.Errorf("fenced line split into %d spans, want 1", len(out[1]))
- }
- if out[1][0].Style.GetForeground() != th.Code {
- t.Errorf("fenced body not code-colored")
- }
-}
-
-func TestScanLeadingFrontmatter(t *testing.T) {
- th := DefaultDarkTheme()
- lines := []string{"---", "title: x", "---", "body"}
- out := ScanLines(lines, th)
- if out[1][0].Style.GetForeground() != th.Blockquote {
- t.Errorf("frontmatter body not muted")
- }
- // after the closing ---, normal text resumes
- if out[3][0].Style.GetForeground() != th.Text {
- t.Errorf("post-frontmatter line should be plain text")
- }
-}
-
-func TestScanEmptyLineYieldsNoSpans(t *testing.T) {
- out := ScanLines([]string{""}, DefaultDarkTheme())
- if len(out[0]) != 0 {
- t.Errorf("empty line should yield no spans, got %d", len(out[0]))
- }
-}
-
-func TestScanHeadingKeepsHashes(t *testing.T) {
- th := DefaultDarkTheme()
- out := ScanLines([]string{"### Title"}, th)
- if spanText(out[0]) != "### Title" {
- t.Errorf("heading hashes dropped: %q", spanText(out[0]))
- }
- if out[0][0].Style.GetForeground() != th.Heading {
- t.Errorf("heading not heading-colored")
- }
-}
-
-func TestScanListMarkerThenInline(t *testing.T) {
- th := DefaultDarkTheme()
- out := ScanLines([]string{"- **x**"}, th)
- if out[0][0].Style.GetForeground() != th.ListMarker {
- t.Errorf("first span should be the list marker, got fg %v", out[0][0].Style.GetForeground())
- }
- if spanText(out[0]) != "- **x**" {
- t.Errorf("list line text altered: %q", spanText(out[0]))
- }
-}
-```
-
-- [ ] **Step 7: Run to verify the scanner tests fail**
-
-Run: `go test ./internal/editor/ -run TestScan`
-Expected: FAIL — `undefined: ScanLines`.
-
-- [ ] **Step 8: Implement the scanner**
-
-Create `internal/editor/scanner.go`:
-```go
-package editor
-
-import (
- "regexp"
- "strings"
-
- "github.com/charmbracelet/lipgloss"
-)
-
-var (
- headingRe = regexp.MustCompile(`^\s*#{1,6}\s`)
- listRe = regexp.MustCompile(`^\s*([-*+]|\d+\.)\s`)
-)
-
-// blockState carries cross-line context (fenced code, leading frontmatter).
-type blockState struct {
- inFence bool
- inFrontmatter bool
- frontmatterDone bool
-}
-
-// ScanLines styles every line, threading block state across lines. The returned
-// slice is parallel to the input: out[i] are the spans for lines[i], whose
-// concatenated text equals lines[i] exactly.
-func ScanLines(lines []string, th Theme) [][]Span {
- st := &blockState{}
- out := make([][]Span, len(lines))
- for i, ln := range lines {
- out[i] = scanLine(i, ln, st, th)
- }
- return out
-}
-
-func scanLine(row int, line string, st *blockState, th Theme) []Span {
- code := lipgloss.NewStyle().Foreground(th.Code)
- muted := lipgloss.NewStyle().Foreground(th.Blockquote)
- trimmed := strings.TrimSpace(line)
-
- // Fenced code block: body lines are entirely code-colored.
- if st.inFence {
- if strings.HasPrefix(trimmed, "```") {
- st.inFence = false
- }
- return wholeLine(line, code)
- }
- if strings.HasPrefix(trimmed, "```") {
- st.inFence = true
- return wholeLine(line, code)
- }
-
- // Leading YAML frontmatter: only valid starting at row 0.
- if st.inFrontmatter {
- if trimmed == "---" {
- st.inFrontmatter = false
- st.frontmatterDone = true
- }
- return wholeLine(line, muted)
- }
- if row == 0 && trimmed == "---" {
- st.inFrontmatter = true
- return wholeLine(line, muted)
- }
-
- // Heading: color the whole line, hashes included.
- if headingRe.MatchString(line) {
- return wholeLine(line, lipgloss.NewStyle().Foreground(th.Heading).Bold(true))
- }
-
- // Blockquote.
- if strings.HasPrefix(trimmed, ">") {
- return wholeLine(line, muted)
- }
-
- // List marker, then inline-scan the remainder.
- if loc := listRe.FindStringIndex(line); loc != nil {
- marker := line[:loc[1]]
- rest := line[loc[1]:]
- spans := []Span{{Text: marker, Style: lipgloss.NewStyle().Foreground(th.ListMarker)}}
- return append(spans, scanInline(rest, th)...)
- }
-
- return scanInline(line, th)
-}
-
-// wholeLine returns a single span for the whole line, or no spans if empty.
-func wholeLine(line string, style lipgloss.Style) []Span {
- if line == "" {
- return nil
- }
- return []Span{{Text: line, Style: style}}
-}
-
-// scanInline emits styled spans for inline constructs, keeping all markup
-// characters visible. Plain text gets the theme's Text foreground.
-func scanInline(text string, th Theme) []Span {
- plain := lipgloss.NewStyle().Foreground(th.Text)
- r := []rune(text)
- var spans []Span
- start, i := 0, 0
- flush := func(end int) {
- if end > start {
- spans = append(spans, Span{Text: string(r[start:end]), Style: plain})
- }
- }
- for i < len(r) {
- if tok, style, n, ok := matchToken(r, i, th); ok {
- flush(i)
- spans = append(spans, Span{Text: tok, Style: style})
- i += n
- start = i
- continue
- }
- i++
- }
- flush(len(r))
- return spans
-}
-
-// matchToken tries to match an inline construct starting at r[i]. It returns the
-// token (including its markup), the style, the rune length, and whether matched.
-func matchToken(r []rune, i int, th Theme) (string, lipgloss.Style, int, bool) {
- // Inline code: `...`
- if r[i] == '`' {
- if j := indexRune(r, '`', i+1); j > i {
- return string(r[i : j+1]), lipgloss.NewStyle().Foreground(th.Code), j + 1 - i, true
- }
- }
- // Wikilink: [[...]]
- if r[i] == '[' && i+1 < len(r) && r[i+1] == '[' {
- if j := indexSeq(r, "]]", i+2); j >= 0 {
- end := j + 2
- return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Wikilink), end - i, true
- }
- }
- // Link: [text](url)
- if r[i] == '[' {
- if c := indexRune(r, ']', i+1); c > i && c+1 < len(r) && r[c+1] == '(' {
- if p := indexRune(r, ')', c+2); p > c {
- end := p + 1
- return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Link), end - i, true
- }
- }
- }
- // Bold: ** or __
- for _, d := range []string{"**", "__"} {
- if hasPrefixRunes(r, i, d) {
- if j := indexSeq(r, d, i+2); j >= 0 {
- end := j + 2
- return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Text).Bold(true), end - i, true
- }
- }
- }
- // Italic: * or _
- if r[i] == '*' || r[i] == '_' {
- if j := indexRune(r, r[i], i+1); j > i {
- end := j + 1
- return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Text).Italic(true), end - i, true
- }
- }
- return "", lipgloss.Style{}, 0, false
-}
-
-func indexRune(r []rune, c rune, from int) int {
- for i := from; i < len(r); i++ {
- if r[i] == c {
- return i
- }
- }
- return -1
-}
-
-func indexSeq(r []rune, seq string, from int) int {
- s := []rune(seq)
- for i := from; i+len(s) <= len(r); i++ {
- match := true
- for k := range s {
- if r[i+k] != s[k] {
- match = false
- break
- }
- }
- if match {
- return i
- }
- }
- return -1
-}
-
-func hasPrefixRunes(r []rune, i int, prefix string) bool {
- p := []rune(prefix)
- if i+len(p) > len(r) {
- return false
- }
- for k := range p {
- if r[i+k] != p[k] {
- return false
- }
- }
- return true
-}
-```
-
-- [ ] **Step 9: Run all editor tests to verify they pass**
-
-Run: `go test ./internal/editor/`
-Expected: PASS (all theme, renderer, and scanner tests).
-
-- [ ] **Step 10: Commit**
-
-```bash
-git add internal/editor/theme.go internal/editor/span.go internal/editor/scanner.go internal/editor/scanner_test.go
-git commit -m "feat: markdown styling scanner with explicit foregrounds"
-```
-
----
-
-## Task 3: Editor buffer, ops, and view
-
-**Files:**
-- Create: `internal/editor/editor.go`
-- Test: `internal/editor/editor_test.go`
-
-**Interfaces:**
-- Consumes: `Span`, `Theme`, `ScanLines`, `renderSpans`, `renderSpansCursor` (Task 2).
-- Produces:
- - `editor.Position` struct `{ Row, Col int }`
- - `editor.Editor` struct (exported fields `Lines []string`, `Cursor Position`, `Scroll int`, `Dirty bool`, `Width int`, `Height int`).
- - `editor.New() *Editor`
- - `func (e *Editor) SetContent(b []byte)` — resets buffer, cursor, scroll, dirty.
- - `func (e *Editor) Bytes() []byte`
- - `func (e *Editor) SetSize(w, h int)`
- - Ops: `InsertRune(r rune)`, `InsertNewline()`, `Backspace()`, `Delete()`, `MoveLeft()`, `MoveRight()`, `MoveUp()`, `MoveDown()`, `MoveHome()`, `MoveEnd()`.
- - `func (e *Editor) HandleKey(k tea.KeyMsg)` — maps keys to ops.
- - `func (e *Editor) View() string`
-
-- [ ] **Step 1: Write the failing test for buffer ops**
-
-Create `internal/editor/editor_test.go`:
-```go
-package editor
-
-import (
- "testing"
-
- tea "github.com/charmbracelet/bubbletea"
-)
-
-func newEditorWith(lines ...string) *Editor {
- e := New()
- e.Lines = append([]string{}, lines...)
- e.SetSize(80, 10)
- return e
-}
-
-func TestSetContentSplitsLines(t *testing.T) {
- e := New()
- e.SetContent([]byte("a\nb\nc"))
- if len(e.Lines) != 3 || e.Lines[1] != "b" {
- t.Fatalf("Lines = %v", e.Lines)
- }
- if e.Dirty {
- t.Error("SetContent should clear Dirty")
- }
-}
-
-func TestBytesRoundTrip(t *testing.T) {
- e := New()
- e.SetContent([]byte("x\ny"))
- if string(e.Bytes()) != "x\ny" {
- t.Errorf("Bytes = %q", string(e.Bytes()))
- }
-}
-
-func TestInsertRune(t *testing.T) {
- e := newEditorWith("ac")
- e.Cursor = Position{Row: 0, Col: 1}
- e.InsertRune('b')
- if e.Lines[0] != "abc" {
- t.Errorf("Lines[0] = %q, want abc", e.Lines[0])
- }
- if e.Cursor.Col != 2 {
- t.Errorf("Cursor.Col = %d, want 2", e.Cursor.Col)
- }
- if !e.Dirty {
- t.Error("insert should set Dirty")
- }
-}
-
-func TestInsertNewlineSplitsLine(t *testing.T) {
- e := newEditorWith("abcd")
- e.Cursor = Position{Row: 0, Col: 2}
- e.InsertNewline()
- if len(e.Lines) != 2 || e.Lines[0] != "ab" || e.Lines[1] != "cd" {
- t.Fatalf("Lines = %v", e.Lines)
- }
- if e.Cursor.Row != 1 || e.Cursor.Col != 0 {
- t.Errorf("Cursor = %+v, want {1 0}", e.Cursor)
- }
-}
-
-func TestBackspaceJoinsLines(t *testing.T) {
- e := newEditorWith("ab", "cd")
- e.Cursor = Position{Row: 1, Col: 0}
- e.Backspace()
- if len(e.Lines) != 1 || e.Lines[0] != "abcd" {
- t.Fatalf("Lines = %v", e.Lines)
- }
- if e.Cursor.Row != 0 || e.Cursor.Col != 2 {
- t.Errorf("Cursor = %+v, want {0 2}", e.Cursor)
- }
-}
-
-func TestBackspaceWithinLine(t *testing.T) {
- e := newEditorWith("abc")
- e.Cursor = Position{Row: 0, Col: 2}
- e.Backspace()
- if e.Lines[0] != "ac" || e.Cursor.Col != 1 {
- t.Errorf("Lines[0]=%q Cursor.Col=%d", e.Lines[0], e.Cursor.Col)
- }
-}
-
-func TestMovementClampsAndCrossesLines(t *testing.T) {
- e := newEditorWith("ab", "cde")
- e.Cursor = Position{Row: 0, Col: 2} // end of "ab"
- e.MoveRight() // wraps to start of next line
- if e.Cursor != (Position{Row: 1, Col: 0}) {
- t.Errorf("after MoveRight: %+v", e.Cursor)
- }
- e.MoveLeft() // back to end of "ab"
- if e.Cursor != (Position{Row: 0, Col: 2}) {
- t.Errorf("after MoveLeft: %+v", e.Cursor)
- }
- e.MoveEnd()
- e.MoveDown() // col clamps to len("cde")=3
- if e.Cursor != (Position{Row: 1, Col: 2}) {
- t.Errorf("after MoveDown: %+v, want {1 2}", e.Cursor)
- }
-}
-
-func TestScrollFollowsCursorDown(t *testing.T) {
- e := New()
- e.SetSize(80, 3) // 3 visible rows
- for i := 0; i < 10; i++ {
- e.Lines = append(e.Lines, "x")
- }
- e.Cursor = Position{Row: 0, Col: 0}
- for i := 0; i < 9; i++ {
- e.MoveDown()
- }
- // cursor at row 9 must be visible within [Scroll, Scroll+3)
- if e.Cursor.Row < e.Scroll || e.Cursor.Row >= e.Scroll+e.Height {
- t.Errorf("cursor row %d not in viewport [%d,%d)", e.Cursor.Row, e.Scroll, e.Scroll+e.Height)
- }
-}
-
-func TestHandleKeyInsertsRunes(t *testing.T) {
- e := newEditorWith("")
- e.HandleKey(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'h', 'i'}})
- if e.Lines[0] != "hi" {
- t.Errorf("Lines[0] = %q, want hi", e.Lines[0])
- }
-}
-
-func TestViewRendersVisibleRowsOnly(t *testing.T) {
- e := New()
- e.SetSize(80, 2)
- e.Lines = []string{"one", "two", "three"}
- e.Cursor = Position{Row: 0, Col: 0}
- view := e.View()
- // 2 visible rows -> exactly 2 newline-terminated lines
- if got := countByte(view, '\n'); got != 2 {
- t.Errorf("view has %d newlines, want 2", got)
- }
-}
-
-func countByte(s string, b byte) int {
- n := 0
- for i := 0; i < len(s); i++ {
- if s[i] == b {
- n++
- }
- }
- return n
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/editor/ -run 'TestSetContent|TestBytes|TestInsert|TestBackspace|TestMovement|TestScroll|TestHandleKey|TestView'`
-Expected: FAIL — `undefined: New`, `undefined: Position`, etc.
-
-- [ ] **Step 3: Implement the editor**
-
-Create `internal/editor/editor.go`:
-```go
-package editor
-
-import (
- "strings"
-
- tea "github.com/charmbracelet/bubbletea"
- "github.com/charmbracelet/lipgloss"
-)
-
-// Position is a cursor location in rune coordinates.
-type Position struct {
- Row, Col int
-}
-
-// Editor is a self-contained markdown text buffer. It knows nothing about
-// files or the vault; the app wires load and save around it.
-type Editor struct {
- Lines []string
- Cursor Position
- Scroll int
- Dirty bool
- Width int
- Height int // visible text rows
- theme Theme
-}
-
-// New returns an empty editor with one blank line and the default theme.
-func New() *Editor {
- return &Editor{
- Lines: []string{""},
- theme: DefaultDarkTheme(),
- Width: 80,
- Height: 24,
- }
-}
-
-// SetContent replaces the buffer, resetting cursor, scroll, and dirty state.
-func (e *Editor) SetContent(b []byte) {
- text := strings.ReplaceAll(string(b), "\r\n", "\n")
- e.Lines = strings.Split(text, "\n")
- if len(e.Lines) == 0 {
- e.Lines = []string{""}
- }
- e.Cursor = Position{}
- e.Scroll = 0
- e.Dirty = false
-}
-
-// Bytes serializes the buffer with \n line separators.
-func (e *Editor) Bytes() []byte {
- return []byte(strings.Join(e.Lines, "\n"))
-}
-
-// SetSize records the viewport dimensions (h = visible text rows).
-func (e *Editor) SetSize(w, h int) {
- e.Width = w
- if h < 1 {
- h = 1
- }
- e.Height = h
- e.followCursor()
-}
-
-func (e *Editor) curLine() []rune { return []rune(e.Lines[e.Cursor.Row]) }
-func (e *Editor) setLine(rs []rune) { e.Lines[e.Cursor.Row] = string(rs) }
-
-// InsertRune inserts r at the cursor and advances it.
-func (e *Editor) InsertRune(r rune) {
- rs := e.curLine()
- col := clamp(e.Cursor.Col, 0, len(rs))
- rs = append(rs[:col], append([]rune{r}, rs[col:]...)...)
- e.setLine(rs)
- e.Cursor.Col = col + 1
- e.Dirty = true
-}
-
-// InsertNewline splits the current line at the cursor.
-func (e *Editor) InsertNewline() {
- rs := e.curLine()
- col := clamp(e.Cursor.Col, 0, len(rs))
- left, right := string(rs[:col]), string(rs[col:])
- e.Lines[e.Cursor.Row] = left
- rest := append([]string{right}, e.Lines[e.Cursor.Row+1:]...)
- e.Lines = append(e.Lines[:e.Cursor.Row+1], rest...)
- e.Cursor.Row++
- e.Cursor.Col = 0
- e.Dirty = true
- e.followCursor()
-}
-
-// Backspace deletes the rune before the cursor, joining lines at column 0.
-func (e *Editor) Backspace() {
- if e.Cursor.Col > 0 {
- rs := e.curLine()
- rs = append(rs[:e.Cursor.Col-1], rs[e.Cursor.Col:]...)
- e.setLine(rs)
- e.Cursor.Col--
- e.Dirty = true
- return
- }
- if e.Cursor.Row == 0 {
- return
- }
- prev := []rune(e.Lines[e.Cursor.Row-1])
- joinCol := len(prev)
- merged := string(prev) + e.Lines[e.Cursor.Row]
- e.Lines[e.Cursor.Row-1] = merged
- e.Lines = append(e.Lines[:e.Cursor.Row], e.Lines[e.Cursor.Row+1:]...)
- e.Cursor.Row--
- e.Cursor.Col = joinCol
- e.Dirty = true
- e.followCursor()
-}
-
-// Delete removes the rune at the cursor, joining the next line at end-of-line.
-func (e *Editor) Delete() {
- rs := e.curLine()
- if e.Cursor.Col < len(rs) {
- rs = append(rs[:e.Cursor.Col], rs[e.Cursor.Col+1:]...)
- e.setLine(rs)
- e.Dirty = true
- return
- }
- if e.Cursor.Row >= len(e.Lines)-1 {
- return
- }
- e.Lines[e.Cursor.Row] = e.Lines[e.Cursor.Row] + e.Lines[e.Cursor.Row+1]
- e.Lines = append(e.Lines[:e.Cursor.Row+1], e.Lines[e.Cursor.Row+2:]...)
- e.Dirty = true
-}
-
-// MoveLeft moves one rune left, wrapping to the end of the previous line.
-func (e *Editor) MoveLeft() {
- if e.Cursor.Col > 0 {
- e.Cursor.Col--
- } else if e.Cursor.Row > 0 {
- e.Cursor.Row--
- e.Cursor.Col = len([]rune(e.Lines[e.Cursor.Row]))
- }
- e.followCursor()
-}
-
-// MoveRight moves one rune right, wrapping to the start of the next line.
-func (e *Editor) MoveRight() {
- if e.Cursor.Col < len(e.curLine()) {
- e.Cursor.Col++
- } else if e.Cursor.Row < len(e.Lines)-1 {
- e.Cursor.Row++
- e.Cursor.Col = 0
- }
- e.followCursor()
-}
-
-// MoveUp moves to the previous line, clamping the column.
-func (e *Editor) MoveUp() {
- if e.Cursor.Row > 0 {
- e.Cursor.Row--
- e.Cursor.Col = clamp(e.Cursor.Col, 0, len([]rune(e.Lines[e.Cursor.Row])))
- }
- e.followCursor()
-}
-
-// MoveDown moves to the next line, clamping the column.
-func (e *Editor) MoveDown() {
- if e.Cursor.Row < len(e.Lines)-1 {
- e.Cursor.Row++
- e.Cursor.Col = clamp(e.Cursor.Col, 0, len([]rune(e.Lines[e.Cursor.Row])))
- }
- e.followCursor()
-}
-
-// MoveHome moves to column 0; MoveEnd to end of line.
-func (e *Editor) MoveHome() { e.Cursor.Col = 0 }
-func (e *Editor) MoveEnd() { e.Cursor.Col = len(e.curLine()) }
-
-// followCursor scrolls the viewport so the cursor row stays visible.
-func (e *Editor) followCursor() {
- if e.Cursor.Row < e.Scroll {
- e.Scroll = e.Cursor.Row
- }
- if e.Cursor.Row >= e.Scroll+e.Height {
- e.Scroll = e.Cursor.Row - e.Height + 1
- }
- if e.Scroll < 0 {
- e.Scroll = 0
- }
-}
-
-// HandleKey maps a key message to a buffer operation.
-func (e *Editor) HandleKey(k tea.KeyMsg) {
- switch k.Type {
- case tea.KeyRunes, tea.KeySpace:
- for _, r := range k.Runes {
- e.InsertRune(r)
- }
- if k.Type == tea.KeySpace {
- e.InsertRune(' ')
- }
- case tea.KeyEnter:
- e.InsertNewline()
- case tea.KeyBackspace:
- e.Backspace()
- case tea.KeyDelete:
- e.Delete()
- case tea.KeyLeft:
- e.MoveLeft()
- case tea.KeyRight:
- e.MoveRight()
- case tea.KeyUp:
- e.MoveUp()
- case tea.KeyDown:
- e.MoveDown()
- case tea.KeyHome:
- e.MoveHome()
- case tea.KeyEnd:
- e.MoveEnd()
- case tea.KeyTab:
- e.InsertRune('\t')
- }
-}
-
-// View renders the visible rows, styled, with the cursor drawn on its row.
-func (e *Editor) View() string {
- cursorStyle := lipgloss.NewStyle().Reverse(true)
- all := ScanLines(e.Lines, e.theme)
- var b strings.Builder
- end := e.Scroll + e.Height
- if end > len(e.Lines) {
- end = len(e.Lines)
- }
- for row := e.Scroll; row < end; row++ {
- if row == e.Cursor.Row {
- b.WriteString(renderSpansCursor(all[row], e.Cursor.Col, cursorStyle))
- } else {
- b.WriteString(renderSpans(all[row]))
- }
- b.WriteByte('\n')
- }
- for row := end; row < e.Scroll+e.Height; row++ {
- b.WriteByte('\n')
- }
- return b.String()
-}
-
-func clamp(v, lo, hi int) int {
- if v < lo {
- return lo
- }
- if v > hi {
- return hi
- }
- return v
-}
-```
-
-- [ ] **Step 4: Run to verify all editor tests pass**
-
-Run: `go test ./internal/editor/`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add internal/editor/editor.go internal/editor/editor_test.go
-git commit -m "feat: editor buffer, ops, and styled view"
-```
-
----
-
-## Task 4: App model — routing, status bar, save/load, quit
-
-**Files:**
-- Create: `internal/app/app.go`
-- Test: `internal/app/app_test.go`
-
-**Interfaces:**
-- Consumes: `config.Config` (Task 1); `editor.New`, `editor.Editor.HandleKey/SetContent/Bytes/SetSize/View`, `editor.Editor.Dirty` (Tasks 2–3).
-- Produces:
- - `app.Mode` int enum: `ModeEditor`, `ModePicker`, `ModePreview`.
- - `app.App` struct implementing `tea.Model` (`Init`, `Update`, `View`).
- - `app.New(cfg config.Config) *App`
- - `func (a *App) Load(path string) error` — reads file into editor, sets `a.path`, switches to `ModeEditor`.
- - `func (a *App) save() (tea.Model, tea.Cmd)` — writes editor bytes to `a.path`.
- - Status-bar rendering in `View`.
- - (Preview/picker wiring is stubbed here and filled in Tasks 5–6. `ModePreview`/`ModePicker` exist now; their keys become active later.)
-
-- [ ] **Step 1: Write the failing test**
-
-Create `internal/app/app_test.go`:
-```go
-package app
-
-import (
- "os"
- "path/filepath"
- "testing"
-
- "glint/internal/config"
-
- tea "github.com/charmbracelet/bubbletea"
-)
-
-func newApp() *App {
- return New(config.Default())
-}
-
-func TestLoadReadsFileIntoEditor(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "n.md")
- os.WriteFile(p, []byte("# hi\nbody"), 0o644)
-
- a := newApp()
- if err := a.Load(p); err != nil {
- t.Fatal(err)
- }
- if a.mode != ModeEditor {
- t.Errorf("mode = %d, want ModeEditor", a.mode)
- }
- if string(a.editor.Bytes()) != "# hi\nbody" {
- t.Errorf("editor content = %q", string(a.editor.Bytes()))
- }
-}
-
-func TestCtrlSSavesToDisk(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "n.md")
- os.WriteFile(p, []byte("old"), 0o644)
-
- a := newApp()
- a.Load(p)
- a.editor.HandleKey(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'!'}})
- if !a.editor.Dirty {
- t.Fatal("expected dirty after edit")
- }
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlS})
-
- got, _ := os.ReadFile(p)
- if string(got) != "!old" {
- t.Errorf("file on disk = %q, want %q", string(got), "!old")
- }
- if a.editor.Dirty {
- t.Error("save should clear dirty")
- }
-}
-
-func TestTypingRoutesToEditor(t *testing.T) {
- a := newApp()
- a.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'x'}})
- if a.editor.Lines[0] != "x" {
- t.Errorf("editor first line = %q, want x", a.editor.Lines[0])
- }
-}
-
-func TestCtrlQCleanQuits(t *testing.T) {
- a := newApp()
- _, cmd := a.Update(tea.KeyMsg{Type: tea.KeyCtrlQ})
- if cmd == nil {
- t.Error("clean buffer Ctrl+Q should return a quit command")
- }
-}
-
-func TestCtrlQDirtyNeedsConfirm(t *testing.T) {
- a := newApp()
- a.editor.HandleKey(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'z'}})
- _, cmd := a.Update(tea.KeyMsg{Type: tea.KeyCtrlQ})
- if cmd != nil {
- t.Error("first dirty Ctrl+Q should not quit")
- }
- _, cmd = a.Update(tea.KeyMsg{Type: tea.KeyCtrlQ})
- if cmd == nil {
- t.Error("second Ctrl+Q should quit")
- }
-}
-
-func TestWindowSizePropagates(t *testing.T) {
- a := newApp()
- a.Update(tea.WindowSizeMsg{Width: 100, Height: 30})
- if a.editor.Width != 100 {
- t.Errorf("editor width = %d, want 100", a.editor.Width)
- }
- if a.editor.Height != 29 { // minus status bar
- t.Errorf("editor height = %d, want 29", a.editor.Height)
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/app/`
-Expected: FAIL — `undefined: New`, `undefined: App`, `undefined: ModeEditor`.
-
-- [ ] **Step 3: Implement the app**
-
-Create `internal/app/app.go`:
-```go
-// Package app is glint's top-level Bubbletea model. It owns the active mode and
-// routes messages to the editor, picker, or preview sub-models.
-package app
-
-import (
- "fmt"
- "os"
-
- "glint/internal/config"
- "glint/internal/editor"
-
- tea "github.com/charmbracelet/bubbletea"
- "github.com/charmbracelet/lipgloss"
-)
-
-// Mode selects which sub-view is active.
-type Mode int
-
-const (
- ModeEditor Mode = iota
- ModePicker
- ModePreview
-)
-
-// App is the root model.
-type App struct {
- mode Mode
- cfg config.Config
- editor *editor.Editor
- path string
- status string
- width int
- height int
-
- quitArmed bool // true after a dirty Ctrl+Q, awaiting confirm
-}
-
-// New builds an App with an empty editor.
-func New(cfg config.Config) *App {
- return &App{
- mode: ModeEditor,
- cfg: cfg,
- editor: editor.New(),
- }
-}
-
-// Load reads a file into the editor and switches to edit mode.
-func (a *App) Load(path string) error {
- data, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- a.editor.SetContent(data)
- a.path = path
- a.mode = ModeEditor
- a.status = path
- return nil
-}
-
-func (a *App) Init() tea.Cmd { return nil }
-
-// Update routes messages. Global keys are handled first, then mode-specific.
-func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
- switch msg := msg.(type) {
- case tea.WindowSizeMsg:
- a.setSize(msg.Width, msg.Height)
- return a, nil
- case tea.KeyMsg:
- return a.handleKey(msg)
- }
- return a, nil
-}
-
-func (a *App) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
- // Any key other than a second Ctrl+Q disarms the quit confirmation.
- if msg.Type != tea.KeyCtrlQ {
- a.quitArmed = false
- }
-
- switch msg.Type {
- case tea.KeyCtrlQ:
- if a.editor.Dirty && !a.quitArmed {
- a.quitArmed = true
- a.status = "Unsaved changes — Ctrl+Q again to quit"
- return a, nil
- }
- return a, tea.Quit
- case tea.KeyCtrlS:
- return a.save()
- }
-
- // Mode-specific routing (picker/preview keys wired in later tasks).
- switch a.mode {
- case ModeEditor:
- a.editor.HandleKey(msg)
- }
- return a, nil
-}
-
-func (a *App) save() (tea.Model, tea.Cmd) {
- if a.path == "" {
- a.status = "No file to save"
- return a, nil
- }
- if err := os.WriteFile(a.path, a.editor.Bytes(), 0o644); err != nil {
- a.status = "Save failed: " + err.Error()
- return a, nil
- }
- a.editor.Dirty = false
- a.status = "Saved " + a.path
- return a, nil
-}
-
-func (a *App) setSize(w, h int) {
- a.width = w
- a.height = h
- a.editor.SetSize(w, h-1) // reserve one row for the status bar
-}
-
-// View renders the active sub-view plus the status bar.
-func (a *App) View() string {
- var body string
- switch a.mode {
- case ModeEditor:
- body = a.editor.View()
- default:
- body = a.editor.View()
- }
- return body + a.statusBar()
-}
-
-func (a *App) statusBar() string {
- bar := lipgloss.NewStyle().
- Foreground(lipgloss.Color("#1a1a24")).
- Background(lipgloss.Color("#7aa2f7")).
- Width(maxInt(a.width, 1))
- dirty := ""
- if a.editor.Dirty {
- dirty = " ●"
- }
- left := a.status
- if left == "" {
- left = "glint"
- }
- return bar.Render(fmt.Sprintf(" %s%s ", left, dirty))
-}
-
-func maxInt(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
-```
-
-- [ ] **Step 4: Run to verify it passes**
-
-Run: `go test ./internal/app/`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add internal/app/
-git commit -m "feat: app model with routing, save/load, quit-confirm, status bar"
-```
-
----
-
-## Task 5: Preview (Glamour read view)
-
-**Files:**
-- Create: `internal/preview/preview.go`
-- Test: `internal/preview/preview_test.go`
-- Modify: `internal/app/app.go` (wire `Ctrl+R` toggle and `Esc`)
-
-**Interfaces:**
-- Consumes: `config.Config.GlamourStyle`.
-- Produces:
- - `preview.Model` struct.
- - `preview.New(style string) *Model`
- - `func (m *Model) SetSize(w, h int)`
- - `func (m *Model) Render(markdown string) error` — Glamour-render into the viewport.
- - `func (m *Model) Update(msg tea.Msg) tea.Cmd` — forwards scroll keys to the viewport.
- - `func (m *Model) View() string`
-- App additions: `Ctrl+R` toggles `ModeEditor`↔`ModePreview` (rendering current buffer); `Esc` returns to `ModeEditor`.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `internal/preview/preview_test.go`:
-```go
-package preview
-
-import (
- "strings"
- "testing"
-)
-
-func TestRenderProducesContent(t *testing.T) {
- m := New("dark")
- m.SetSize(80, 20)
- if err := m.Render("# Title\n\nsome **bold** text"); err != nil {
- t.Fatal(err)
- }
- out := m.View()
- if strings.TrimSpace(out) == "" {
- t.Error("preview view is empty after Render")
- }
- if !strings.Contains(out, "Title") {
- t.Errorf("rendered output missing heading text: %q", out)
- }
-}
-
-func TestRenderUnknownStyleFallsBack(t *testing.T) {
- m := New("definitely-not-a-real-style")
- m.SetSize(80, 20)
- if err := m.Render("hello"); err != nil {
- t.Errorf("unknown style should fall back, got error %v", err)
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/preview/`
-Expected: FAIL — `undefined: New`.
-
-- [ ] **Step 3: Implement the preview**
-
-Create `internal/preview/preview.go`:
-```go
-// Package preview renders the current buffer through Glamour into a scrollable,
-// read-only viewport — the full glow read experience, markup concealed.
-package preview
-
-import (
- "os"
-
- tea "github.com/charmbracelet/bubbletea"
- "github.com/charmbracelet/bubbles/viewport"
- "github.com/charmbracelet/glamour"
-)
-
-// Model wraps a Glamour renderer and a viewport.
-type Model struct {
- vp viewport.Model
- style string
- width int
- height int
-}
-
-// New returns a preview using the given Glamour style (builtin name or a path
-// to a style JSON file).
-func New(style string) *Model {
- return &Model{
- vp: viewport.New(0, 0),
- style: style,
- width: 80,
- height: 24,
- }
-}
-
-// SetSize resizes the viewport.
-func (m *Model) SetSize(w, h int) {
- m.width = w
- if h < 1 {
- h = 1
- }
- m.height = h
- m.vp.Width = w
- m.vp.Height = h
-}
-
-// Render runs markdown through Glamour and loads it into the viewport.
-func (m *Model) Render(markdown string) error {
- r, err := m.renderer()
- if err != nil {
- return err
- }
- out, err := r.Render(markdown)
- if err != nil {
- return err
- }
- m.vp.SetContent(out)
- m.vp.GotoTop()
- return nil
-}
-
-// renderer builds a Glamour renderer, treating m.style as a file path when it
-// exists on disk and as a builtin style name otherwise.
-func (m *Model) renderer() (*glamour.TermRenderer, error) {
- width := m.width
- if width < 1 {
- width = 80
- }
- opts := []glamour.TermRendererOption{glamour.WithWordWrap(width)}
- if _, err := os.Stat(m.style); err == nil {
- opts = append(opts, glamour.WithStylePath(m.style))
- } else {
- opts = append(opts, glamour.WithStandardStyle(m.style))
- }
- return glamour.NewTermRenderer(opts...)
-}
-
-// Update forwards scroll keys to the viewport.
-func (m *Model) Update(msg tea.Msg) tea.Cmd {
- var cmd tea.Cmd
- m.vp, cmd = m.vp.Update(msg)
- return cmd
-}
-
-// View renders the viewport.
-func (m *Model) View() string { return m.vp.View() }
-```
-
-- [ ] **Step 4: Run to verify it passes**
-
-Run: `go test ./internal/preview/`
-Expected: PASS.
-
-NOTE: if `glamour.WithStandardStyle` errors on an unknown name at render time rather than falling back, the test `TestRenderUnknownStyleFallsBack` will catch it. If it fails, change `renderer()` to fall back to `glamour.WithStandardStyle("dark")` when the requested builtin name is not one of glamour's known styles (`ascii`, `dark`, `light`, `dracula`, `tokyo-night`, `notty`, `pink`). Implement the fallback as: keep a `map[string]bool` of known names; if `m.style` is neither an existing file nor a known name, use `"dark"`.
-
-- [ ] **Step 5: Wire the preview into the app**
-
-In `internal/app/app.go`, add the import and a `preview` field, construct it in `New`, propagate size, and handle `Ctrl+R`/`Esc`.
-
-Add to imports:
-```go
- "glint/internal/preview"
-```
-
-Add field to `App` struct (after `editor *editor.Editor`):
-```go
- preview *preview.Model
-```
-
-In `New`, set it:
-```go
-func New(cfg config.Config) *App {
- return &App{
- mode: ModeEditor,
- cfg: cfg,
- editor: editor.New(),
- preview: preview.New(cfg.GlamourStyle),
- }
-}
-```
-
-In `setSize`, also size the preview:
-```go
-func (a *App) setSize(w, h int) {
- a.width = w
- a.height = h
- a.editor.SetSize(w, h-1)
- a.preview.SetSize(w, h-1)
-}
-```
-
-In `handleKey`, add a `Ctrl+R` case and an `Esc` case before the mode switch. Replace the global-key switch with:
-```go
- switch msg.Type {
- case tea.KeyCtrlQ:
- if a.editor.Dirty && !a.quitArmed {
- a.quitArmed = true
- a.status = "Unsaved changes — Ctrl+Q again to quit"
- return a, nil
- }
- return a, tea.Quit
- case tea.KeyCtrlS:
- return a.save()
- case tea.KeyCtrlR:
- return a.togglePreview()
- case tea.KeyEsc:
- a.mode = ModeEditor
- return a, nil
- }
-
- switch a.mode {
- case ModeEditor:
- a.editor.HandleKey(msg)
- case ModePreview:
- return a, a.preview.Update(msg)
- }
- return a, nil
-```
-
-Add the toggle method:
-```go
-// togglePreview switches between the editor and the Glamour read view.
-func (a *App) togglePreview() (tea.Model, tea.Cmd) {
- if a.mode == ModePreview {
- a.mode = ModeEditor
- return a, nil
- }
- if err := a.preview.Render(string(a.editor.Bytes())); err != nil {
- a.status = "Preview failed: " + err.Error()
- return a, nil
- }
- a.mode = ModePreview
- return a, nil
-}
-```
-
-Update `View` to render the preview when active:
-```go
-func (a *App) View() string {
- var body string
- switch a.mode {
- case ModePreview:
- body = a.preview.View()
- default:
- body = a.editor.View()
- }
- return body + a.statusBar()
-}
-```
-
-- [ ] **Step 6: Add an app test for the preview toggle**
-
-Append to `internal/app/app_test.go`:
-```go
-func TestCtrlRTogglesPreview(t *testing.T) {
- a := newApp()
- a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
- a.editor.SetContent([]byte("# hello"))
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlR})
- if a.mode != ModePreview {
- t.Errorf("mode = %d, want ModePreview", a.mode)
- }
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlR})
- if a.mode != ModeEditor {
- t.Errorf("mode = %d, want ModeEditor after second toggle", a.mode)
- }
-}
-
-func TestEscReturnsToEditor(t *testing.T) {
- a := newApp()
- a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
- a.editor.SetContent([]byte("x"))
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlR})
- a.Update(tea.KeyMsg{Type: tea.KeyEsc})
- if a.mode != ModeEditor {
- t.Errorf("Esc should return to editor, mode = %d", a.mode)
- }
-}
-```
-
-- [ ] **Step 7: Run preview and app tests**
-
-Run: `go test ./internal/preview/ ./internal/app/`
-Expected: PASS.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add internal/preview/ internal/app/
-git commit -m "feat: glamour read-preview with Ctrl+R toggle"
-```
-
----
-
-## Task 6: Picker (fuzzy file browser) + daily note
-
-**Files:**
-- Create: `internal/picker/picker.go`
-- Test: `internal/picker/picker_test.go`
-- Modify: `internal/app/app.go` (wire `Ctrl+P` picker, `Ctrl+D` daily, `Enter` selection)
-
-**Interfaces:**
-- Consumes: `config.Config` (for `DailyPath` and `VaultDir`).
-- Produces:
- - `picker.fuzzyMatch(query, candidate string) (score int, ok bool)` — unexported, pure, tested.
- - `picker.walkMarkdown(root string) ([]string, error)` — unexported; absolute `.md` paths, skipping dot-directories.
- - `picker.Model` struct.
- - `picker.New(root string) (*Model, error)`
- - `func (m *Model) SetSize(w, h int)`
- - `func (m *Model) Update(msg tea.Msg) tea.Cmd` — updates the query input, recomputes matches, moves selection on Up/Down.
- - `func (m *Model) Selected() string` — absolute path of the highlighted match, or `""`.
- - `func (m *Model) View() string`
-- App additions: `Ctrl+P` enters `ModePicker`; `Ctrl+D` opens/creates today's daily note; in `ModePicker`, `Enter` loads `Selected()`.
-
-- [ ] **Step 1: Write the failing test for the pure helpers**
-
-Create `internal/picker/picker_test.go`:
-```go
-package picker
-
-import (
- "os"
- "path/filepath"
- "sort"
- "testing"
-)
-
-func TestFuzzyMatchSubsequence(t *testing.T) {
- if _, ok := fuzzyMatch("abc", "axbxc"); !ok {
- t.Error("abc should match axbxc as a subsequence")
- }
- if _, ok := fuzzyMatch("abc", "acb"); ok {
- t.Error("abc should NOT match acb (out of order)")
- }
- if _, ok := fuzzyMatch("", "anything"); !ok {
- t.Error("empty query should match anything")
- }
-}
-
-func TestFuzzyMatchCaseInsensitive(t *testing.T) {
- if _, ok := fuzzyMatch("DOC", "my-document"); !ok {
- t.Error("DOC should match my-document case-insensitively")
- }
-}
-
-func TestFuzzyMatchContiguousScoresHigher(t *testing.T) {
- tight, ok1 := fuzzyMatch("ab", "abxx")
- loose, ok2 := fuzzyMatch("ab", "axxb")
- if !ok1 || !ok2 {
- t.Fatal("both should match")
- }
- if tight <= loose {
- t.Errorf("contiguous match (%d) should score higher than gapped (%d)", tight, loose)
- }
-}
-
-func TestWalkMarkdownSkipsDotDirsAndNonMarkdown(t *testing.T) {
- root := t.TempDir()
- os.WriteFile(filepath.Join(root, "a.md"), nil, 0o644)
- os.WriteFile(filepath.Join(root, "b.txt"), nil, 0o644)
- os.MkdirAll(filepath.Join(root, ".git"), 0o755)
- os.WriteFile(filepath.Join(root, ".git", "c.md"), nil, 0o644)
- os.MkdirAll(filepath.Join(root, "sub"), 0o755)
- os.WriteFile(filepath.Join(root, "sub", "d.md"), nil, 0o644)
-
- got, err := walkMarkdown(root)
- if err != nil {
- t.Fatal(err)
- }
- sort.Strings(got)
- want := []string{
- filepath.Join(root, "a.md"),
- filepath.Join(root, "sub", "d.md"),
- }
- if len(got) != len(want) {
- t.Fatalf("walkMarkdown = %v, want %v", got, want)
- }
- for i := range want {
- if got[i] != want[i] {
- t.Errorf("got[%d] = %q, want %q", i, got[i], want[i])
- }
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/picker/`
-Expected: FAIL — `undefined: fuzzyMatch`, `undefined: walkMarkdown`.
-
-- [ ] **Step 3: Implement the picker**
-
-Create `internal/picker/picker.go`:
-```go
-// Package picker is a fuzzy file browser over a directory of markdown files.
-package picker
-
-import (
- "io/fs"
- "path/filepath"
- "sort"
- "strings"
-
- "github.com/charmbracelet/bubbles/textinput"
- tea "github.com/charmbracelet/bubbletea"
- "github.com/charmbracelet/lipgloss"
-)
-
-// Model holds the query input and the current match list.
-type Model struct {
- input textinput.Model
- all []string // absolute .md paths
- root string
- matches []string
- sel int
- width int
- height int
-}
-
-// New walks root for markdown files and returns a ready picker.
-func New(root string) (*Model, error) {
- files, err := walkMarkdown(root)
- if err != nil {
- return nil, err
- }
- ti := textinput.New()
- ti.Placeholder = "filter…"
- ti.Focus()
- m := &Model{input: ti, all: files, root: root, width: 80, height: 24}
- m.recompute()
- return m, nil
-}
-
-// SetSize records dimensions.
-func (m *Model) SetSize(w, h int) {
- m.width = w
- m.height = h
-}
-
-// Update handles query edits and selection movement.
-func (m *Model) Update(msg tea.Msg) tea.Cmd {
- if key, ok := msg.(tea.KeyMsg); ok {
- switch key.Type {
- case tea.KeyUp:
- if m.sel > 0 {
- m.sel--
- }
- return nil
- case tea.KeyDown:
- if m.sel < len(m.matches)-1 {
- m.sel++
- }
- return nil
- }
- }
- var cmd tea.Cmd
- m.input, cmd = m.input.Update(msg)
- m.recompute()
- return cmd
-}
-
-// recompute filters and ranks all paths against the current query.
-func (m *Model) recompute() {
- q := m.input.Value()
- type scored struct {
- path string
- score int
- }
- var hits []scored
- for _, p := range m.all {
- label := m.label(p)
- if s, ok := fuzzyMatch(q, label); ok {
- hits = append(hits, scored{p, s})
- }
- }
- sort.SliceStable(hits, func(i, j int) bool {
- if hits[i].score != hits[j].score {
- return hits[i].score > hits[j].score
- }
- return hits[i].path < hits[j].path
- })
- m.matches = m.matches[:0]
- for _, h := range hits {
- m.matches = append(m.matches, h.path)
- }
- if m.sel >= len(m.matches) {
- m.sel = 0
- }
-}
-
-// label is the vault-relative path shown to the user and matched against.
-func (m *Model) label(p string) string {
- if rel, err := filepath.Rel(m.root, p); err == nil {
- return rel
- }
- return p
-}
-
-// Selected returns the highlighted match's absolute path, or "".
-func (m *Model) Selected() string {
- if m.sel < 0 || m.sel >= len(m.matches) {
- return ""
- }
- return m.matches[m.sel]
-}
-
-// View renders the query line and the match list.
-func (m *Model) View() string {
- var b strings.Builder
- b.WriteString(m.input.View())
- b.WriteByte('\n')
- selStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#1a1a24")).Background(lipgloss.Color("#e0af68"))
- plain := lipgloss.NewStyle().Foreground(lipgloss.Color("#c0caf5"))
- rows := m.height - 2
- if rows < 1 {
- rows = 1
- }
- for i := 0; i < len(m.matches) && i < rows; i++ {
- label := m.label(m.matches[i])
- if i == m.sel {
- b.WriteString(selStyle.Render("> " + label))
- } else {
- b.WriteString(plain.Render(" " + label))
- }
- b.WriteByte('\n')
- }
- return b.String()
-}
-
-// walkMarkdown returns absolute paths of .md files under root, skipping any
-// directory whose name begins with a dot.
-func walkMarkdown(root string) ([]string, error) {
- var out []string
- err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return nil // skip unreadable entries
- }
- if d.IsDir() {
- if path != root && strings.HasPrefix(d.Name(), ".") {
- return filepath.SkipDir
- }
- return nil
- }
- if strings.EqualFold(filepath.Ext(d.Name()), ".md") {
- abs, aerr := filepath.Abs(path)
- if aerr == nil {
- out = append(out, abs)
- }
- }
- return nil
- })
- return out, err
-}
-
-// fuzzyMatch reports whether query is a case-insensitive subsequence of
-// candidate, scoring contiguous matches higher (fewer gaps -> higher score).
-func fuzzyMatch(query, candidate string) (int, bool) {
- if query == "" {
- return 0, true
- }
- q := []rune(strings.ToLower(query))
- c := []rune(strings.ToLower(candidate))
- score, qi, last := 0, 0, -1
- for ci := 0; ci < len(c) && qi < len(q); ci++ {
- if c[ci] == q[qi] {
- if last >= 0 {
- score -= ci - last - 1 // penalize gaps
- }
- last = ci
- qi++
- }
- }
- if qi != len(q) {
- return 0, false
- }
- return score, true
-}
-```
-
-- [ ] **Step 4: Run picker tests to verify they pass**
-
-Run: `go test ./internal/picker/`
-Expected: PASS.
-
-- [ ] **Step 5: Wire the picker and daily note into the app**
-
-In `internal/app/app.go`:
-
-Add imports:
-```go
- "path/filepath"
- "time"
-
- "glint/internal/picker"
-```
-
-Add a field to `App` (after `preview`):
-```go
- picker *picker.Model
-```
-
-Add `Ctrl+P`, `Ctrl+D` cases and picker `Enter` routing. In `handleKey`, extend the global switch:
-```go
- case tea.KeyCtrlP:
- return a.openPicker()
- case tea.KeyCtrlD:
- return a.openDaily()
-```
-
-And change the mode switch to handle picker keys, with `Enter` selecting:
-```go
- switch a.mode {
- case ModeEditor:
- a.editor.HandleKey(msg)
- case ModePreview:
- return a, a.preview.Update(msg)
- case ModePicker:
- if msg.Type == tea.KeyEnter {
- if sel := a.picker.Selected(); sel != "" {
- if err := a.Load(sel); err != nil {
- a.status = "Open failed: " + err.Error()
- }
- }
- return a, nil
- }
- return a, a.picker.Update(msg)
- }
- return a, nil
-```
-
-Add the helper methods:
-```go
-// openPicker builds a fresh picker over the vault and switches to it.
-func (a *App) openPicker() (tea.Model, tea.Cmd) {
- p, err := picker.New(a.cfg.VaultDir)
- if err != nil {
- a.status = "Picker failed: " + err.Error()
- return a, nil
- }
- p.SetSize(a.width, a.height-1)
- a.picker = p
- a.mode = ModePicker
- return a, nil
-}
-
-// openDaily opens today's daily note, creating the file and directory if needed.
-func (a *App) openDaily() (tea.Model, tea.Cmd) {
- path := a.cfg.DailyPath(time.Now())
- if _, err := os.Stat(path); os.IsNotExist(err) {
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- a.status = "Daily dir failed: " + err.Error()
- return a, nil
- }
- if err := os.WriteFile(path, []byte{}, 0o644); err != nil {
- a.status = "Daily create failed: " + err.Error()
- return a, nil
- }
- }
- if err := a.Load(path); err != nil {
- a.status = "Daily open failed: " + err.Error()
- }
- return a, nil
-}
-```
-
-Update `View` to render the picker when active:
-```go
-func (a *App) View() string {
- var body string
- switch a.mode {
- case ModePreview:
- body = a.preview.View()
- case ModePicker:
- body = a.picker.View()
- default:
- body = a.editor.View()
- }
- return body + a.statusBar()
-}
-```
-
-Guard the `quitArmed` reset and `Esc` so they don't fire while typing in the picker query: the existing `Esc` case already returns to `ModeEditor`, which is the desired "cancel picker" behavior. Leave it.
-
-- [ ] **Step 6: Add app tests for picker and daily**
-
-Append to `internal/app/app_test.go`:
-```go
-func TestCtrlPOpensPicker(t *testing.T) {
- dir := t.TempDir()
- os.WriteFile(filepath.Join(dir, "note.md"), []byte("x"), 0o644)
- cfg := config.Default()
- cfg.VaultDir = dir
- a := New(cfg)
- a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlP})
- if a.mode != ModePicker {
- t.Errorf("mode = %d, want ModePicker", a.mode)
- }
-}
-
-func TestCtrlDCreatesAndOpensDaily(t *testing.T) {
- dir := t.TempDir()
- cfg := config.Default()
- cfg.VaultDir = dir
- cfg.DailySubdir = "Daily"
- cfg.DailyFormat = "2006-01-02"
- a := New(cfg)
- a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
- if a.mode != ModeEditor {
- t.Errorf("mode = %d, want ModeEditor after daily open", a.mode)
- }
- if a.path == "" {
- t.Error("daily path should be set")
- }
- if _, err := os.Stat(a.path); err != nil {
- t.Errorf("daily file should exist on disk: %v", err)
- }
-}
-```
-
-Add the missing import to the app test file's import block: `"path/filepath"` (already present from Task 4's tests) and `"glint/internal/config"` (already present).
-
-- [ ] **Step 7: Run picker and app tests**
-
-Run: `go test ./internal/picker/ ./internal/app/`
-Expected: PASS.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add internal/picker/ internal/app/
-git commit -m "feat: fuzzy file picker (Ctrl+P) and daily note (Ctrl+D)"
-```
-
----
-
-## Task 7: Entrypoint and end-to-end wiring
-
-**Files:**
-- Create: `main.go`
-- Test: manual smoke (no automated test — `main` is thin glue over tested units).
-
-**Interfaces:**
-- Consumes: `config.Load`, `app.New`, `app.App.Load`, and (for `--daily`) the same daily-note creation path used by the app. To avoid duplicating the daily logic, `main` does NOT recreate the daily file; it sets a flag the app honors on the first frame.
-- Produces: the `glint` binary.
-
-To keep the daily logic in one place, add one small method to the app that `main` calls.
-
-- [ ] **Step 1: Add an app entry helper (test-first)**
-
-Append to `internal/app/app_test.go`:
-```go
-func TestStartInPickerWhenNoPath(t *testing.T) {
- dir := t.TempDir()
- os.WriteFile(filepath.Join(dir, "n.md"), []byte("x"), 0o644)
- cfg := config.Default()
- cfg.VaultDir = dir
- a := New(cfg)
- if err := a.Start("", false); err != nil {
- t.Fatal(err)
- }
- if a.mode != ModePicker {
- t.Errorf("no path/daily should start in picker, mode = %d", a.mode)
- }
-}
-
-func TestStartWithPathLoadsFile(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "n.md")
- os.WriteFile(p, []byte("hello"), 0o644)
- a := New(config.Default())
- if err := a.Start(p, false); err != nil {
- t.Fatal(err)
- }
- if a.mode != ModeEditor || string(a.editor.Bytes()) != "hello" {
- t.Errorf("Start(path) should load file into editor")
- }
-}
-
-func TestStartDailyCreatesFile(t *testing.T) {
- dir := t.TempDir()
- cfg := config.Default()
- cfg.VaultDir = dir
- a := New(cfg)
- if err := a.Start("", true); err != nil {
- t.Fatal(err)
- }
- if a.mode != ModeEditor || a.path == "" {
- t.Errorf("Start(daily) should open the daily note")
- }
- if _, err := os.Stat(a.path); err != nil {
- t.Errorf("daily file should exist: %v", err)
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/app/ -run TestStart`
-Expected: FAIL — `undefined: (*App).Start`.
-
-- [ ] **Step 3: Implement `Start` and refactor daily creation**
-
-In `internal/app/app.go`, factor the daily file creation into a helper and add `Start`. Replace `openDaily` with a version that calls the shared helper, and add `Start`:
-```go
-// Start picks the initial view: an explicit path, today's daily note, or the
-// picker when neither is given.
-func (a *App) Start(path string, daily bool) error {
- switch {
- case path != "":
- return a.Load(path)
- case daily:
- _, cmd := a.openDaily()
- _ = cmd
- return nil
- default:
- _, cmd := a.openPicker()
- _ = cmd
- return nil
- }
-}
-```
-
-(`openDaily` and `openPicker` already set `a.status` on failure and never return an error; `Start` surfaces hard load errors only for the explicit-path case, which is the one a user can mistype.)
-
-- [ ] **Step 4: Run to verify it passes**
-
-Run: `go test ./internal/app/`
-Expected: PASS.
-
-- [ ] **Step 5: Write the entrypoint**
-
-Create `main.go`:
-```go
-// Command glint is a modeless terminal markdown editor with live styling.
-package main
-
-import (
- "flag"
- "fmt"
- "os"
-
- "glint/internal/app"
- "glint/internal/config"
-
- tea "github.com/charmbracelet/bubbletea"
-)
-
-func main() {
- daily := flag.Bool("daily", false, "open today's daily note")
- flag.Parse()
-
- cfg, err := config.Load()
- if err != nil {
- fmt.Fprintln(os.Stderr, "glint: config:", err)
- }
-
- var path string
- if args := flag.Args(); len(args) > 0 {
- path = args[0]
- }
-
- a := app.New(cfg)
- if err := a.Start(path, *daily); err != nil {
- fmt.Fprintln(os.Stderr, "glint:", err)
- os.Exit(1)
- }
-
- if _, err := tea.NewProgram(a, tea.WithAltScreen()).Run(); err != nil {
- fmt.Fprintln(os.Stderr, "glint:", err)
- os.Exit(1)
- }
-}
-```
-
-- [ ] **Step 6: Build, vet, and run the full test suite**
-
-Run:
-```bash
-go vet ./...
-go build ./...
-go test ./...
-```
-Expected: no vet errors, a built binary, all tests PASS.
-
-- [ ] **Step 7: Manual smoke test**
-
-Run:
-```bash
-go run . README.md
-```
-Expected: README opens in the editor with headings/bold/links styled and the markup characters visible; arrows move the cursor; typing inserts; `Ctrl+R` shows the glamour preview; `Esc` returns; `Ctrl+P` opens the fuzzy picker; `Ctrl+D` opens today's daily note; `Ctrl+S` saves; `Ctrl+Q` quits (twice if dirty).
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add main.go internal/app/
-git commit -m "feat: glint entrypoint (path / --daily / picker) and Start wiring"
-```
-
----
-
-## Self-Review Notes
-
-**Spec coverage check:**
-- Modeless editing → Task 3 (`HandleKey`, no modes).
-- Live inline styling, markup not concealed → Task 2 (scanner, markup-visible invariant test) + Task 3 (`View`).
-- Explicit foreground on every span (ekphos fix) → Task 2 (`TestScanPlainTextGetsExplicitForeground`, theme).
-- Editor knows nothing about files → Task 3 (no file I/O in `editor`); load/save in Task 4.
-- Block context (fences, frontmatter) → Task 2 (`blockState`, dedicated tests).
-- Glamour preview, markup concealed → Task 5.
-- Fuzzy picker → Task 6 (`fuzzyMatch`, `walkMarkdown`).
-- Daily note with configurable subdir/format → Tasks 1 (`DailyPath`) + 6/7 (`openDaily`, `Start`).
-- TOML config, defaults, malformed handling → Task 1.
-- Keybinds (Ctrl+S/P/D/R, Esc, Ctrl+Q confirm) → Tasks 4–6.
-- Error handling surfaced in status bar, never silent → Task 4 (`save`, `status`), Tasks 5–6 (status on failure).
-- Entrypoint flags (path, --daily, bare → picker) → Task 7.
-
-**Out of scope (v1), per spec — intentionally absent:** wikilink follow (styled only), in-content search, graph, tag browsing, sort persistence, vim modality, the later Vault TUI layer.
-
-**Type consistency:** `Editor` exported fields and method names are used identically across Tasks 3–7. `Mode` constants (`ModeEditor`, `ModePicker`, `ModePreview`) are defined once in Task 4 and referenced unchanged. `picker.Model.Selected()`, `preview.Model.Render/Update/View`, and `config.Config.DailyPath` signatures match their call sites.
-
-**Known follow-ups (not v1 blockers):** the heading scanner colors all heading levels identically (spec allows per-level later); `glamour` style-name fallback has a documented contingency in Task 5 Step 4; module path `glint` is local-only (change to a `github.com/...` path if the project is ever published).
docs/superpowers/plans/2026-06-28-glint-theme-picker.md +0 −1704
@@ -1,1713 +0,0 @@
-# glint v1.1 — Theme System + Picker Overhaul Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Add light/dark/charm themes (OS auto-detect + `Ctrl+T` live toggle), rework the file picker to sort by modified-date with today's daily floated on top plus a live glamour preview pane and `Ctrl+N` new-note, and syntax-highlight YAML frontmatter.
-
-**Architecture:** Extract theming into a standalone `internal/theme` package consumed by `editor`, `picker`, `app`, and `preview` (no import cycles). The app holds the active `theme.Theme` and pushes it into sub-models; `Ctrl+T` cycles it. The picker gains mtime-aware ranking, a today-float, a split layout with a glamour preview pane, and a new-note path builder. The scanner's frontmatter branch gains per-element coloring while preserving the char-for-char invariant.
-
-**Tech Stack:** Go 1.26, Bubbletea, Bubbles (viewport, textinput), Lipgloss, Glamour, BurntSushi/toml — all already in go.mod at the newest resolver-selected versions.
-
-## Global Constraints
-
-- Module path `glint`; internal packages import as `glint/internal/<pkg>`.
-- **Dependency policy:** use the newest versions Go's resolver selects; do not pin to specific numbers. Do not flag a dependency version as a defect.
-- **Explicit-foreground invariant (now load-bearing for light themes):** every emitted styled span — in every theme — gets an explicit `Foreground`. Never `lipgloss.Style{}` / terminal default.
-- **Markup-visible invariant:** the editor styling scanner never inserts or deletes characters; the concatenation of a line's span texts equals the raw line exactly. This includes the new YAML-frontmatter highlighting.
-- Three themes only: `flexoki-light`, `flexoki-dark`, `charm`. Exact hexes are specified in Task 1 — copy them verbatim.
-- `theme` config values: `auto` (default), `flexoki-light`, `flexoki-dark`, `charm`. `auto` → OS detection; unknown → OS detection (never errors).
-- macOS detection: `defaults read -g AppleInterfaceStyle`; output containing `Dark` → dark, else light. Non-darwin → `flexoki-dark`.
-- Theme cycle order (`Ctrl+T`): `flexoki-light → flexoki-dark → charm → flexoki-light`.
-- New keybinds: `Ctrl+T` cycle theme (global); `Ctrl+N` new note (picker mode). All v1 keybinds and the v1.0 confirm-then-discard behavior unchanged.
-- Out of scope: full-text/ripgrep picker mode; new-note template seeding.
-- TDD per task: write failing test → run (fails) → implement → run (passes) → commit. Each task ends `go vet ./...` clean and the full `go test ./...` green before commit.
-
----
-
-## File Structure
-
-```
-internal/theme/ NEW package — single source of theme truth
- theme.go Theme struct, registry, ByName, Next, Resolve, CycleOrder
- themes.go FlexokiLight(), FlexokiDark(), Charm() — concrete palettes
- detect.go Detect() + detectFrom() (deterministic parse)
- theme_test.go all-fields-set per theme; ByName; Resolve; Next/cycle
- detect_test.go detectFrom parse cases
-internal/editor/
- theme.go DELETED (moved to internal/theme)
- scanner.go MOD: take theme.Theme; frontmatter highlighting (Task 3)
- editor.go MOD: theme field is theme.Theme; New() default FlexokiDark; SetTheme
- scanner_test.go MOD: use theme.Theme/FlexokiDark; frontmatter corpus (Task 3)
-internal/config/
- config.go MOD: Theme field (toml `theme`, default "auto"); GlamourStyle default ""
- config_test.go MOD: theme default + overlay; glamour default ""
-internal/preview/
- preview.go MOD: add SetStyle(string)
-internal/picker/
- picker.go MOD: fileEntry+mtime walk, rankEntries, today-float, theme colors,
- preview pane, Query(), SetTheme/SetStyle, NewNotePath
- picker_test.go MOD: walkMarkdown returns mtime; rankEntries ordering; NewNotePath
-internal/app/
- app.go MOD: active theme; Ctrl+T cycle; theme→editor/picker/status/glamour;
- Ctrl+N new note; pass theme+todayPath+style into picker.New
- app_test.go MOD: Ctrl+T cycles; Ctrl+N creates+opens; picker still opens/dismisses
-```
-
----
-
-## Task 1: `internal/theme` package
-
-**Files:**
-- Create: `internal/theme/theme.go`, `internal/theme/themes.go`, `internal/theme/detect.go`
-- Test: `internal/theme/theme_test.go`, `internal/theme/detect_test.go`
-
-**Interfaces:**
-- Consumes: nothing (pure, leaf package; only lipgloss + stdlib).
-- Produces:
- - `theme.Theme` struct (fields below).
- - `theme.FlexokiLight() Theme`, `theme.FlexokiDark() Theme`, `theme.Charm() Theme`.
- - `theme.CycleOrder []string` = `{"flexoki-light","flexoki-dark","charm"}`.
- - `theme.ByName(name string) (Theme, bool)`.
- - `theme.Next(name string) Theme` — next theme in CycleOrder, wrapping.
- - `theme.Resolve(configValue string) Theme`.
- - `theme.Detect() string`, internal `detectFrom(raw string) string`.
-
-- [ ] **Step 1: Write the failing tests**
-
-Create `internal/theme/theme_test.go`:
-```go
-package theme
-
-import (
- "testing"
-
- "github.com/charmbracelet/lipgloss"
-)
-
-func allThemes() []Theme { return []Theme{FlexokiLight(), FlexokiDark(), Charm()} }
-
-func TestEveryThemeHasAllColorsSet(t *testing.T) {
- for _, th := range allThemes() {
- colors := map[string]lipgloss.Color{
- "Text": th.Text, "Heading": th.Heading, "Code": th.Code, "Link": th.Link,
- "Wikilink": th.Wikilink, "ListMarker": th.ListMarker, "Blockquote": th.Blockquote,
- "Accent": th.Accent, "Background": th.Background, "Muted": th.Muted,
- "StatusFg": th.StatusFg, "StatusBg": th.StatusBg, "SelFg": th.SelFg,
- "SelBg": th.SelBg, "Pointer": th.Pointer,
- }
- for name, c := range colors {
- if c == "" {
- t.Errorf("theme %q: color %s is empty", th.Name, name)
- }
- }
- if th.Name == "" {
- t.Error("theme has empty Name")
- }
- if th.GlamourStyle == "" {
- t.Errorf("theme %q has empty GlamourStyle", th.Name)
- }
- }
-}
-
-func TestByName(t *testing.T) {
- for _, name := range CycleOrder {
- if _, ok := ByName(name); !ok {
- t.Errorf("ByName(%q) not found", name)
- }
- }
- if _, ok := ByName("nope"); ok {
- t.Error("ByName(nope) should not be found")
- }
-}
-
-func TestNextCycles(t *testing.T) {
- if Next("flexoki-light").Name != "flexoki-dark" {
- t.Error("light -> dark")
- }
- if Next("flexoki-dark").Name != "charm" {
- t.Error("dark -> charm")
- }
- if Next("charm").Name != "flexoki-light" {
- t.Error("charm -> light (wrap)")
- }
- // Unknown name starts the cycle at the first entry's successor is well-defined:
- if Next("unknown").Name != CycleOrder[0] {
- t.Errorf("unknown -> %s, want %s", Next("unknown").Name, CycleOrder[0])
- }
-}
-
-func TestResolve(t *testing.T) {
- if Resolve("charm").Name != "charm" {
- t.Error("explicit name should resolve to itself")
- }
- // auto and unknown both fall back to OS detection — must be a real registered theme.
- for _, v := range []string{"auto", "", "bogus"} {
- got := Resolve(v)
- if _, ok := ByName(got.Name); !ok {
- t.Errorf("Resolve(%q) returned unregistered theme %q", v, got.Name)
- }
- }
-}
-```
-
-Create `internal/theme/detect_test.go`:
-```go
-package theme
-
-import "testing"
-
-func TestDetectFrom(t *testing.T) {
- cases := map[string]string{
- "Dark\n": "flexoki-dark",
- "Dark": "flexoki-dark",
- "": "flexoki-light", // macOS light mode leaves the key unset (empty output)
- "Light": "flexoki-light",
- }
- for raw, want := range cases {
- if got := detectFrom(raw); got != want {
- t.Errorf("detectFrom(%q) = %q, want %q", raw, got, want)
- }
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/theme/`
-Expected: FAIL — `undefined: FlexokiLight`, `undefined: Theme`, etc.
-
-- [ ] **Step 3: Implement `theme.go`**
-
-Create `internal/theme/theme.go`:
-```go
-// Package theme is glint's single source of color truth. Every styled span in
-// every theme gets an explicit foreground — no terminal-default fallbacks — so
-// the editor reads cleanly on both light and dark terminals.
-package theme
-
-import "github.com/charmbracelet/lipgloss"
-
-// Theme holds every color glint paints, plus its name and the glamour style the
-// read-preview should use to stay visually in sync.
-type Theme struct {
- Name string
- GlamourStyle string
-
- // Markdown element colors.
- Text lipgloss.Color
- Heading lipgloss.Color
- Code lipgloss.Color
- Link lipgloss.Color
- Wikilink lipgloss.Color
- ListMarker lipgloss.Color
- Blockquote lipgloss.Color
- Accent lipgloss.Color
-
- // UI colors.
- Background lipgloss.Color
- Muted lipgloss.Color
- StatusFg lipgloss.Color
- StatusBg lipgloss.Color
- SelFg lipgloss.Color
- SelBg lipgloss.Color
- Pointer lipgloss.Color
-}
-
-// CycleOrder is the order Ctrl+T steps through themes.
-var CycleOrder = []string{"flexoki-light", "flexoki-dark", "charm"}
-
-func registry() map[string]Theme {
- return map[string]Theme{
- "flexoki-light": FlexokiLight(),
- "flexoki-dark": FlexokiDark(),
- "charm": Charm(),
- }
-}
-
-// ByName looks up a registered theme.
-func ByName(name string) (Theme, bool) {
- t, ok := registry()[name]
- return t, ok
-}
-
-// Next returns the theme after name in CycleOrder, wrapping around. An unknown
-// name yields the first theme in the cycle.
-func Next(name string) Theme {
- idx := 0
- for i, n := range CycleOrder {
- if n == name {
- idx = (i + 1) % len(CycleOrder)
- break
- }
- }
- t, _ := ByName(CycleOrder[idx])
- return t
-}
-
-// Resolve picks a theme from a config value: "auto"/"" → OS detection; a known
-// name → that theme; an unknown name → OS detection. It never errors and never
-// returns an empty theme.
-func Resolve(configValue string) Theme {
- if configValue == "" || configValue == "auto" {
- t, _ := ByName(Detect())
- return t
- }
- if t, ok := ByName(configValue); ok {
- return t
- }
- t, _ := ByName(Detect())
- return t
-}
-```
-
-- [ ] **Step 4: Implement `themes.go`**
-
-Create `internal/theme/themes.go`:
-```go
-package theme
-
-import "github.com/charmbracelet/lipgloss"
-
-// FlexokiDark is Steph Ango's Flexoki palette, dark variant. Hexes match the
-// user's `md` navigator and the vault ontology.
-func FlexokiDark() Theme {
- return Theme{
- Name: "flexoki-dark",
- GlamourStyle: "dark",
- Text: lipgloss.Color("#CECDC3"),
- Heading: lipgloss.Color("#4385BE"),
- Code: lipgloss.Color("#879A39"),
- Link: lipgloss.Color("#3AA99F"),
- Wikilink: lipgloss.Color("#8B7EC8"),
- ListMarker: lipgloss.Color("#CE5D97"),
- Blockquote: lipgloss.Color("#878580"),
- Accent: lipgloss.Color("#D0A215"),
- Background: lipgloss.Color("#100F0F"),
- Muted: lipgloss.Color("#878580"),
- StatusFg: lipgloss.Color("#100F0F"),
- StatusBg: lipgloss.Color("#4385BE"),
- SelFg: lipgloss.Color("#100F0F"),
- SelBg: lipgloss.Color("#D0A215"),
- Pointer: lipgloss.Color("#CE5D97"),
- }
-}
-
-// FlexokiLight is the Flexoki light variant — the fix for unreadable text on
-// cream/light terminals.
-func FlexokiLight() Theme {
- return Theme{
- Name: "flexoki-light",
- GlamourStyle: "light",
- Text: lipgloss.Color("#100F0F"),
- Heading: lipgloss.Color("#205EA6"),
- Code: lipgloss.Color("#66800B"),
- Link: lipgloss.Color("#24837B"),
- Wikilink: lipgloss.Color("#5E409D"),
- ListMarker: lipgloss.Color("#A02F6F"),
- Blockquote: lipgloss.Color("#6F6E69"),
- Accent: lipgloss.Color("#AD8301"),
- Background: lipgloss.Color("#FFFCF0"),
- Muted: lipgloss.Color("#6F6E69"),
- StatusFg: lipgloss.Color("#FFFCF0"),
- StatusBg: lipgloss.Color("#205EA6"),
- SelFg: lipgloss.Color("#FFFCF0"),
- SelBg: lipgloss.Color("#AD8301"),
- Pointer: lipgloss.Color("#A02F6F"),
- }
-}
-
-// Charm is a charm.land / charmbracelet-brand themed dark palette.
-func Charm() Theme {
- return Theme{
- Name: "charm",
- GlamourStyle: "dark",
- Text: lipgloss.Color("#FFFDF5"),
- Heading: lipgloss.Color("#FF5FAF"),
- Code: lipgloss.Color("#00FFA3"),
- Link: lipgloss.Color("#5DD5FF"),
- Wikilink: lipgloss.Color("#B575FF"),
- ListMarker: lipgloss.Color("#FF5FAF"),
- Blockquote: lipgloss.Color("#6C6C8A"),
- Accent: lipgloss.Color("#FFD500"),
- Background: lipgloss.Color("#16161E"),
- Muted: lipgloss.Color("#6C6C8A"),
- StatusFg: lipgloss.Color("#FFFDF5"),
- StatusBg: lipgloss.Color("#6B50FF"),
- SelFg: lipgloss.Color("#16161E"),
- SelBg: lipgloss.Color("#FF5FAF"),
- Pointer: lipgloss.Color("#00FFA3"),
- }
-}
-```
-
-- [ ] **Step 5: Implement `detect.go`**
-
-Create `internal/theme/detect.go`:
-```go
-package theme
-
-import (
- "os/exec"
- "runtime"
- "strings"
-)
-
-// Detect returns "flexoki-dark" or "flexoki-light" from the OS appearance. On
-// non-darwin platforms it returns dark. On macOS it reads the global
-// AppleInterfaceStyle key (unset in Light mode → empty output → light).
-func Detect() string {
- if runtime.GOOS != "darwin" {
- return "flexoki-dark"
- }
- out, _ := exec.Command("defaults", "read", "-g", "AppleInterfaceStyle").Output()
- return detectFrom(string(out))
-}
-
-// detectFrom parses the raw `defaults read -g AppleInterfaceStyle` output.
-func detectFrom(raw string) string {
- if strings.Contains(raw, "Dark") {
- return "flexoki-dark"
- }
- return "flexoki-light"
-}
-```
-
-- [ ] **Step 6: Run to verify it passes**
-
-Run: `go test ./internal/theme/`
-Expected: PASS.
-
-- [ ] **Step 7: Vet and commit**
-
-```bash
-go vet ./internal/theme/
-git add internal/theme/
-git commit -m "feat: theme package — flexoki light/dark + charm, detect, resolve"
-```
-
----
-
-## Task 2: Migrate `editor` to `theme.Theme`
-
-**Files:**
-- Delete: `internal/editor/theme.go`
-- Modify: `internal/editor/scanner.go`, `internal/editor/editor.go`
-- Modify: `internal/editor/scanner_test.go`
-
-**Interfaces:**
-- Consumes: `theme.Theme`, `theme.FlexokiDark` (Task 1).
-- Produces:
- - `ScanLines(lines []string, th theme.Theme) [][]Span` (param type changed).
- - `(*Editor).SetTheme(t theme.Theme)`.
- - `editor.New() *Editor` unchanged signature; default theme is now `theme.FlexokiDark()`.
-
-This is a mechanical type move. The frontmatter still renders all-muted here; Task 3 changes that.
-
-- [ ] **Step 1: Delete the old theme file**
-
-```bash
-git rm internal/editor/theme.go
-```
-
-- [ ] **Step 2: Update `scanner.go` to use `theme.Theme`**
-
-In `internal/editor/scanner.go`, add the import and change every `Theme` to `theme.Theme`. The import block becomes:
-```go
-import (
- "regexp"
- "strings"
-
- "glint/internal/theme"
-
- "github.com/charmbracelet/lipgloss"
-)
-```
-Change these four signatures (bodies unchanged — they already use `th.Code`, `th.Heading`, etc., which exist on `theme.Theme`):
-```go
-func ScanLines(lines []string, th theme.Theme) [][]Span {
-```
-```go
-func scanLine(row int, line string, st *blockState, th theme.Theme) []Span {
-```
-```go
-func scanInline(text string, th theme.Theme) []Span {
-```
-```go
-func matchToken(r []rune, i int, th theme.Theme) (string, lipgloss.Style, int, bool) {
-```
-
-- [ ] **Step 3: Update `editor.go` to use `theme.Theme` and add `SetTheme`**
-
-In `internal/editor/editor.go`, add the import:
-```go
-import (
- "strings"
-
- "glint/internal/theme"
-
- tea "github.com/charmbracelet/bubbletea"
- "github.com/charmbracelet/lipgloss"
-)
-```
-Change the struct field:
-```go
- theme theme.Theme
-```
-Change `New` to default to FlexokiDark:
-```go
-func New() *Editor {
- return &Editor{
- Lines: []string{""},
- theme: theme.FlexokiDark(),
- Width: 80,
- Height: 24,
- }
-}
-```
-Add the setter (place it right after `New`):
-```go
-// SetTheme swaps the active theme; the next View re-scans with the new colors.
-func (e *Editor) SetTheme(t theme.Theme) { e.theme = t }
-```
-
-- [ ] **Step 4: Update `scanner_test.go`**
-
-In `internal/editor/scanner_test.go`: add the import `"glint/internal/theme"`, replace every `DefaultDarkTheme()` with `theme.FlexokiDark()`, and **delete** `TestDefaultThemeAllColorsSet` entirely (that invariant now lives in `internal/theme/theme_test.go`). Leave the `lipgloss` import only if still used (it is, by `TestRenderSpansPreservesText` and `TestScanPlainTextGetsExplicitForeground`). The frontmatter test (`TestScanLeadingFrontmatter`) stays as-is — frontmatter is still all-muted in this task.
-
-- [ ] **Step 5: Run editor + whole suite**
-
-Run: `go test ./internal/editor/`
-Expected: PASS (frontmatter still muted; everything else unchanged).
-
-Run: `go test ./...`
-Expected: PASS — `app` and `preview` still compile (they don't reference `editor.Theme`).
-
-- [ ] **Step 6: Vet and commit**
-
-```bash
-go vet ./...
-git add internal/editor/
-git commit -m "refactor: editor consumes theme.Theme; default flexoki-dark; SetTheme"
-```
-
----
-
-## Task 3: YAML frontmatter highlighting
-
-**Files:**
-- Modify: `internal/editor/scanner.go`
-- Modify: `internal/editor/scanner_test.go`
-
-**Interfaces:**
-- Consumes: `theme.Theme` (Task 2). Uses fields `Accent` (keys), `Text` (values), `ListMarker` (`-` markers), `Muted`/`Blockquote` (delimiters, comments).
-- Produces: no new exported symbols; the frontmatter branch of `scanLine` now emits multiple colored spans instead of one muted span.
-
-Preserve the markup-visible invariant: spans for a line concatenate back to the raw line exactly.
-
-- [ ] **Step 1: Write the failing tests**
-
-Append to `internal/editor/scanner_test.go`:
-```go
-func TestScanFrontmatterHighlightsKeysAndValues(t *testing.T) {
- th := theme.FlexokiDark()
- lines := []string{"---", "title: Hello", "tags:", " - one", " - two", "# a comment", "---", "body"}
- out := ScanLines(lines, th)
-
- // Char-for-char preservation across every frontmatter line.
- for i, raw := range lines {
- if got := spanText(out[i]); got != raw {
- t.Errorf("line %d: span text %q != raw %q", i, got, raw)
- }
- }
- // Opening and closing --- are muted.
- if out[0][0].Style.GetForeground() != th.Muted {
- t.Errorf("opening --- not muted")
- }
- if out[6][0].Style.GetForeground() != th.Muted {
- t.Errorf("closing --- not muted")
- }
- // "title:" key portion is Accent; the value is Text.
- if out[1][0].Style.GetForeground() != th.Accent {
- t.Errorf("key not Accent-colored, got %v", out[1][0].Style.GetForeground())
- }
- if last := out[1][len(out[1])-1]; last.Style.GetForeground() != th.Text {
- t.Errorf("value not Text-colored, got %v", last.Style.GetForeground())
- }
- // List item marker "-" is ListMarker-colored.
- foundMarker := false
- for _, sp := range out[3] {
- if sp.Style.GetForeground() == th.ListMarker {
- foundMarker = true
- }
- }
- if !foundMarker {
- t.Errorf("list item dash not ListMarker-colored")
- }
- // Comment line is muted.
- if out[5][0].Style.GetForeground() != th.Muted {
- t.Errorf("comment not muted")
- }
- // After the closing ---, normal text resumes.
- if out[7][0].Style.GetForeground() != th.Text {
- t.Errorf("post-frontmatter line should be plain text")
- }
-}
-```
-Also **replace** the existing `TestScanLeadingFrontmatter` body (its old expectation that `title: x` is muted is now wrong). Replace it with:
-```go
-func TestScanLeadingFrontmatter(t *testing.T) {
- th := theme.FlexokiDark()
- lines := []string{"---", "title: x", "---", "body"}
- out := ScanLines(lines, th)
- if out[0][0].Style.GetForeground() != th.Muted {
- t.Errorf("opening --- not muted")
- }
- if out[1][0].Style.GetForeground() != th.Accent {
- t.Errorf("frontmatter key not accent-colored")
- }
- if out[3][0].Style.GetForeground() != th.Text {
- t.Errorf("post-frontmatter line should be plain text")
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/editor/ -run TestScanFrontmatter`
-Expected: FAIL — frontmatter currently renders one muted span, so the key is muted, not Accent.
-
-- [ ] **Step 3: Implement frontmatter highlighting**
-
-In `internal/editor/scanner.go`, replace the frontmatter block inside `scanLine`. The current block is:
-```go
- // Leading YAML frontmatter: only valid starting at row 0.
- if st.inFrontmatter {
- if trimmed == "---" {
- st.inFrontmatter = false
- st.frontmatterDone = true
- }
- return wholeLine(line, muted)
- }
- if row == 0 && trimmed == "---" {
- st.inFrontmatter = true
- return wholeLine(line, muted)
- }
-```
-Replace it with:
-```go
- // Leading YAML frontmatter: only valid starting at row 0.
- if st.inFrontmatter {
- if trimmed == "---" {
- st.inFrontmatter = false
- st.frontmatterDone = true
- return wholeLine(line, muted)
- }
- return scanFrontmatter(line, th)
- }
- if row == 0 && trimmed == "---" {
- st.inFrontmatter = true
- return wholeLine(line, muted)
- }
-```
-Then add this function near `wholeLine` (after it):
-```go
-// scanFrontmatter highlights one YAML frontmatter line, keeping every character
-// visible: the spans concatenate back to the raw line exactly.
-// - "# comment" -> whole line muted
-// - " - item" -> leading ws + dash (ListMarker) + item (Text)
-// - "key: value" -> "key:" (Accent) + " value" (Text)
-// - anything else -> whole line Text
-func scanFrontmatter(line string, th theme.Theme) []Span {
- muted := lipgloss.NewStyle().Foreground(th.Blockquote)
- accent := lipgloss.NewStyle().Foreground(th.Accent)
- plain := lipgloss.NewStyle().Foreground(th.Text)
- marker := lipgloss.NewStyle().Foreground(th.ListMarker)
-
- trimmed := strings.TrimSpace(line)
-
- // Comment line.
- if strings.HasPrefix(trimmed, "#") {
- return wholeLine(line, muted)
- }
-
- // List item: optional leading whitespace, then "- ...".
- if loc := listRe.FindStringIndex(line); loc != nil && strings.HasPrefix(trimmed, "-") {
- mk := line[:loc[1]] // leading ws + "- "
- rest := line[loc[1]:] // item text
- spans := []Span{{Text: mk, Style: marker}}
- if rest != "" {
- spans = append(spans, Span{Text: rest, Style: plain})
- }
- return spans
- }
-
- // key: value — split at the first colon. Keep the colon with the key.
- if idx := strings.IndexByte(line, ':'); idx >= 0 {
- key := line[:idx+1] // includes the colon
- rest := line[idx+1:] // remainder (may start with a space)
- spans := []Span{{Text: key, Style: accent}}
- if rest != "" {
- spans = append(spans, Span{Text: rest, Style: plain})
- }
- return spans
- }
-
- // Bare line (e.g. a continuation): plain text.
- return wholeLine(line, plain)
-}
-```
-
-- [ ] **Step 4: Run editor tests**
-
-Run: `go test ./internal/editor/`
-Expected: PASS (new frontmatter test + replaced test + all prior tests).
-
-- [ ] **Step 5: Vet and commit**
-
-```bash
-go vet ./...
-git add internal/editor/scanner.go internal/editor/scanner_test.go
-git commit -m "feat: syntax-highlight YAML frontmatter (keys/values/markers/comments)"
-```
-
----
-
-## Task 4: Config `theme` key, app active theme, `Ctrl+T` toggle, glamour sync
-
-**Files:**
-- Modify: `internal/config/config.go`, `internal/config/config_test.go`
-- Modify: `internal/preview/preview.go`
-- Modify: `internal/app/app.go`, `internal/app/app_test.go`
-
-**Interfaces:**
-- Consumes: `theme.Resolve`, `theme.Next`, `theme.Theme` (Task 1); `(*editor.Editor).SetTheme` (Task 2).
-- Produces:
- - `config.Config.Theme string` (toml `theme`, default `"auto"`); `GlamourStyle` default becomes `""`.
- - `(*preview.Model).SetStyle(s string)`.
- - App holds `theme theme.Theme`; `Ctrl+T` cycles; status bar uses theme colors; glamour style derived from theme unless `cfg.GlamourStyle` set.
-
-- [ ] **Step 1: Write the failing config test**
-
-In `internal/config/config_test.go`, update `TestDefaultHasSaneValues` to also assert the new defaults — append inside it:
-```go
- if d.Theme != "auto" {
- t.Errorf("Theme = %q, want auto", d.Theme)
- }
- if d.GlamourStyle != "" {
- t.Errorf("GlamourStyle default = %q, want empty (theme drives it)", d.GlamourStyle)
- }
-```
-And add a new test:
-```go
-func TestLoadFromFileOverlaysTheme(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "config.toml")
- if err := os.WriteFile(path, []byte("theme = \"charm\"\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- cfg, err := loadFromFile(path)
- if err != nil {
- t.Fatal(err)
- }
- if cfg.Theme != "charm" {
- t.Errorf("Theme = %q, want charm", cfg.Theme)
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/config/`
-Expected: FAIL — `d.Theme` undefined; default GlamourStyle is `"dark"` not `""`.
-
-- [ ] **Step 3: Update `config.go`**
-
-In `internal/config/config.go`, add the field to the struct:
-```go
-type Config struct {
- VaultDir string `toml:"vault_dir"`
- DailySubdir string `toml:"daily_subdir"`
- DailyFormat string `toml:"daily_format"`
- GlamourStyle string `toml:"glamour_style"`
- Theme string `toml:"theme"`
-}
-```
-Change `Default()` — set `Theme: "auto"` and drop the `GlamourStyle` default (leave it `""`):
-```go
-func Default() Config {
- home, _ := os.UserHomeDir()
- return Config{
- VaultDir: filepath.Join(home, "Humdrum"),
- DailySubdir: "Daily",
- DailyFormat: "2006-01-02",
- Theme: "auto",
- }
-}
-```
-In `loadFromFile`, add a Theme overlay alongside the existing ones (GlamourStyle overlay stays — an explicitly-set non-empty value still overrides):
-```go
- if fileCfg.Theme != "" {
- cfg.Theme = fileCfg.Theme
- }
-```
-
-- [ ] **Step 4: Run config tests**
-
-Run: `go test ./internal/config/`
-Expected: PASS.
-
-- [ ] **Step 5: Add `SetStyle` to preview**
-
-In `internal/preview/preview.go`, add after `SetSize`:
-```go
-// SetStyle changes the glamour style used by the next Render.
-func (m *Model) SetStyle(s string) { m.style = s }
-```
-
-- [ ] **Step 6: Write the failing app test**
-
-Append to `internal/app/app_test.go`:
-```go
-func TestCtrlTCyclesTheme(t *testing.T) {
- cfg := config.Default()
- cfg.Theme = "flexoki-light"
- a := New(cfg)
- a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
- if a.theme.Name != "flexoki-light" {
- t.Fatalf("initial theme = %q, want flexoki-light", a.theme.Name)
- }
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlT})
- if a.theme.Name != "flexoki-dark" {
- t.Errorf("after one Ctrl+T = %q, want flexoki-dark", a.theme.Name)
- }
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlT})
- if a.theme.Name != "charm" {
- t.Errorf("after two Ctrl+T = %q, want charm", a.theme.Name)
- }
-}
-```
-
-- [ ] **Step 7: Run to verify it fails**
-
-Run: `go test ./internal/app/ -run TestCtrlTCyclesTheme`
-Expected: FAIL — `a.theme` undefined.
-
-- [ ] **Step 8: Wire the theme into the app**
-
-In `internal/app/app.go`:
-
-Add the import:
-```go
- "glint/internal/theme"
-```
-Add a field to `App` (after `cfg`):
-```go
- theme theme.Theme
-```
-Rewrite `New` to resolve the theme, push it into the editor, and derive the glamour style:
-```go
-func New(cfg config.Config) *App {
- th := theme.Resolve(cfg.Theme)
- ed := editor.New()
- ed.SetTheme(th)
- a := &App{
- mode: ModeEditor,
- cfg: cfg,
- theme: th,
- editor: ed,
- }
- a.preview = preview.New(a.glamourStyle())
- return a
-}
-
-// glamourStyle is the explicit config override if set, else the theme's style.
-func (a *App) glamourStyle() string {
- if a.cfg.GlamourStyle != "" {
- return a.cfg.GlamourStyle
- }
- return a.theme.GlamourStyle
-}
-```
-Add a `Ctrl+T` case to the global key switch (after the `Ctrl+R` case):
-```go
- case tea.KeyCtrlT:
- return a.cycleTheme()
-```
-Add the cycle handler (near `togglePreview`):
-```go
-// cycleTheme advances to the next theme and repaints the editor, preview, and
-// (if open) the picker.
-func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
- a.theme = theme.Next(a.theme.Name)
- a.editor.SetTheme(a.theme)
- a.preview.SetStyle(a.glamourStyle())
- if a.picker != nil {
- a.picker.SetTheme(a.theme)
- a.picker.SetStyle(a.glamourStyle())
- }
- a.status = "Theme: " + a.theme.Name
- return a, nil
-}
-```
-Update `statusBar` to use theme colors:
-```go
-func (a *App) statusBar() string {
- bar := lipgloss.NewStyle().
- Foreground(a.theme.StatusFg).
- Background(a.theme.StatusBg).
- Width(maxInt(a.width, 1))
- dirty := ""
- if a.editor.Dirty {
- dirty = " ●"
- }
- left := a.status
- if left == "" {
- left = "glint"
- }
- return bar.Render(fmt.Sprintf(" %s%s ", left, dirty))
-}
-```
-
-> NOTE: `a.picker.SetTheme` / `a.picker.SetStyle` are added in Task 5. Until then the picker has no `SetTheme`. To keep this task compiling and committable on its own, the `if a.picker != nil` block above will not compile yet. Therefore, in THIS task, write the `cycleTheme` body WITHOUT the picker block:
-> ```go
-> func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
-> a.theme = theme.Next(a.theme.Name)
-> a.editor.SetTheme(a.theme)
-> a.preview.SetStyle(a.glamourStyle())
-> a.status = "Theme: " + a.theme.Name
-> return a, nil
-> }
-> ```
-> Task 5 re-adds the picker repaint lines once `SetTheme`/`SetStyle` exist on the picker.
-
-- [ ] **Step 9: Run app + whole suite**
-
-Run: `go test ./internal/app/ ./internal/config/ ./internal/preview/`
-Expected: PASS.
-
-Run: `go test ./...`
-Expected: PASS.
-
-- [ ] **Step 10: Vet and commit**
-
-```bash
-go vet ./...
-git add internal/config/ internal/preview/ internal/app/
-git commit -m "feat: theme config key, Ctrl+T cycle, themed status bar, glamour sync"
-```
-
----
-
-## Task 5: Picker — mtime sort, today-float, theme colors
-
-**Files:**
-- Modify: `internal/picker/picker.go`, `internal/picker/picker_test.go`
-- Modify: `internal/app/app.go` (pass theme + today path into `picker.New`; re-add picker repaint in `cycleTheme`)
-
-**Interfaces:**
-- Consumes: `theme.Theme` (Task 1); `config.Config.DailyPath` (existing).
-- Produces:
- - `picker.fileEntry struct { path string; mod time.Time }` (unexported).
- - `walkMarkdown(root string) ([]fileEntry, error)` (return type changed).
- - `rankEntries(all []fileEntry, query, today string) []string` (pure, tested).
- - `picker.New(root string, th theme.Theme, todayPath string) (*Model, error)` (signature changed).
- - `(*Model).SetTheme(t theme.Theme)`, `(*Model).Query() string`.
- - `(*Model).Selected()`, `SetSize`, `Update`, `View` unchanged signatures.
-
-(The preview pane and `SetStyle`/`NewNotePath` arrive in Tasks 6–7. This task delivers ordering + theming with a list-only View.)
-
-- [ ] **Step 1: Write the failing tests**
-
-Replace the body of `TestWalkMarkdownSkipsDotDirsAndNonMarkdown` in `internal/picker/picker_test.go` to account for the new return type — change the result extraction to read `.path`:
-```go
-func TestWalkMarkdownSkipsDotDirsAndNonMarkdown(t *testing.T) {
- root := t.TempDir()
- os.WriteFile(filepath.Join(root, "a.md"), nil, 0o644)
- os.WriteFile(filepath.Join(root, "b.txt"), nil, 0o644)
- os.MkdirAll(filepath.Join(root, ".git"), 0o755)
- os.WriteFile(filepath.Join(root, ".git", "c.md"), nil, 0o644)
- os.MkdirAll(filepath.Join(root, "sub"), 0o755)
- os.WriteFile(filepath.Join(root, "sub", "d.md"), nil, 0o644)
-
- entries, err := walkMarkdown(root)
- if err != nil {
- t.Fatal(err)
- }
- var got []string
- for _, e := range entries {
- got = append(got, e.path)
- }
- sort.Strings(got)
- want := []string{
- filepath.Join(root, "a.md"),
- filepath.Join(root, "sub", "d.md"),
- }
- if len(got) != len(want) {
- t.Fatalf("walkMarkdown = %v, want %v", got, want)
- }
- for i := range want {
- if got[i] != want[i] {
- t.Errorf("got[%d] = %q, want %q", i, got[i], want[i])
- }
- }
-}
-```
-Add ranking tests (pure, no filesystem):
-```go
-func TestRankEntriesMtimeDescending(t *testing.T) {
- base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
- all := []fileEntry{
- {path: "/v/old.md", mod: base},
- {path: "/v/new.md", mod: base.Add(48 * time.Hour)},
- {path: "/v/mid.md", mod: base.Add(24 * time.Hour)},
- }
- got := rankEntries(all, "", "")
- want := []string{"/v/new.md", "/v/mid.md", "/v/old.md"}
- for i := range want {
- if got[i] != want[i] {
- t.Errorf("got[%d] = %q, want %q", i, got[i], want[i])
- }
- }
-}
-
-func TestRankEntriesTodayFloatsToTop(t *testing.T) {
- base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
- all := []fileEntry{
- {path: "/v/new.md", mod: base.Add(48 * time.Hour)},
- {path: "/v/Daily/2026-06-28.md", mod: base}, // oldest, but today
- }
- got := rankEntries(all, "", "/v/Daily/2026-06-28.md")
- if got[0] != "/v/Daily/2026-06-28.md" {
- t.Errorf("today's note should float to top, got %q", got[0])
- }
-}
-
-func TestRankEntriesQueryFiltersAndTieBreaksByMtime(t *testing.T) {
- base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
- all := []fileEntry{
- {path: "/v/alpha.md", mod: base},
- {path: "/v/alpha-new.md", mod: base.Add(24 * time.Hour)},
- {path: "/v/zzz.md", mod: base.Add(72 * time.Hour)},
- }
- got := rankEntries(all, "alpha", "")
- // zzz filtered out; both "alpha" files present, newer first on equal score is
- // not guaranteed (scores differ), but zzz must be absent.
- for _, p := range got {
- if p == "/v/zzz.md" {
- t.Error("zzz.md should not match query 'alpha'")
- }
- }
- if len(got) != 2 {
- t.Fatalf("got %d matches, want 2", len(got))
- }
-}
-```
-Add `"time"` to the test file's imports.
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/picker/`
-Expected: FAIL — `fileEntry` undefined, `rankEntries` undefined, `walkMarkdown` returns `[]string`.
-
-- [ ] **Step 3: Rewrite `picker.go` (ordering + theming, list-only View)**
-
-Replace the entire contents of `internal/picker/picker.go` with:
-```go
-// Package picker is a fuzzy file browser over a directory of markdown files.
-// It sorts by modified-date (newest first), floats today's daily note to the
-// top, and paints with the active theme.
-package picker
-
-import (
- "io/fs"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "glint/internal/theme"
-
- "github.com/charmbracelet/bubbles/textinput"
- tea "github.com/charmbracelet/bubbletea"
- "github.com/charmbracelet/lipgloss"
-)
-
-// fileEntry is a markdown file plus its modification time.
-type fileEntry struct {
- path string
- mod time.Time
-}
-
-// Model holds the query input, the file set, and the current match list.
-type Model struct {
- input textinput.Model
- all []fileEntry
- root string
- todayPath string
- matches []string
- sel int
- width int
- height int
- theme theme.Theme
-}
-
-// New walks root for markdown files and returns a ready picker themed by th.
-// todayPath is the absolute path of today's daily note (floated to the top when
-// present); pass "" if there is none.
-func New(root string, th theme.Theme, todayPath string) (*Model, error) {
- files, err := walkMarkdown(root)
- if err != nil {
- return nil, err
- }
- ti := textinput.New()
- ti.Prompt = "note › "
- ti.Placeholder = "filter…"
- ti.Focus()
- m := &Model{
- input: ti,
- all: files,
- root: root,
- todayPath: todayPath,
- width: 80,
- height: 24,
- theme: th,
- }
- m.recompute()
- return m, nil
-}
-
-// SetSize records dimensions.
-func (m *Model) SetSize(w, h int) {
- m.width = w
- m.height = h
-}
-
-// SetTheme repaints the picker with a new theme.
-func (m *Model) SetTheme(t theme.Theme) { m.theme = t }
-
-// Query returns the current filter text (used by the app's new-note shortcut).
-func (m *Model) Query() string { return m.input.Value() }
-
-// Update handles query edits and selection movement.
-func (m *Model) Update(msg tea.Msg) tea.Cmd {
- if key, ok := msg.(tea.KeyMsg); ok {
- switch key.Type {
- case tea.KeyUp:
- if m.sel > 0 {
- m.sel--
- }
- return nil
- case tea.KeyDown:
- if m.sel < len(m.matches)-1 {
- m.sel++
- }
- return nil
- }
- }
- var cmd tea.Cmd
- m.input, cmd = m.input.Update(msg)
- m.recompute()
- return cmd
-}
-
-// recompute refilters and reranks against the current query.
-func (m *Model) recompute() {
- m.matches = rankEntries(m.all, m.input.Value(), m.todayPath)
- if m.sel >= len(m.matches) {
- m.sel = 0
- }
-}
-
-// rankEntries filters all entries by the fuzzy query and orders the survivors.
-// Empty query: today's note first, then modified-date descending. Non-empty:
-// fuzzy score descending, then modified-date descending.
-func rankEntries(all []fileEntry, query, today string) []string {
- type scored struct {
- e fileEntry
- score int
- }
- var hits []scored
- for _, e := range all {
- label := filepath.Base(e.path)
- if s, ok := fuzzyMatch(query, label); ok {
- hits = append(hits, scored{e, s})
- }
- }
- sort.SliceStable(hits, func(i, j int) bool {
- if query == "" {
- ti := hits[i].e.path == today
- tj := hits[j].e.path == today
- if ti != tj {
- return ti // today's note floats up
- }
- return hits[i].e.mod.After(hits[j].e.mod)
- }
- if hits[i].score != hits[j].score {
- return hits[i].score > hits[j].score
- }
- return hits[i].e.mod.After(hits[j].e.mod)
- })
- out := make([]string, 0, len(hits))
- for _, h := range hits {
- out = append(out, h.e.path)
- }
- return out
-}
-
-// label is the vault-relative path shown to the user.
-func (m *Model) label(p string) string {
- if rel, err := filepath.Rel(m.root, p); err == nil {
- return rel
- }
- return p
-}
-
-// Selected returns the highlighted match's absolute path, or "".
-func (m *Model) Selected() string {
- if m.sel < 0 || m.sel >= len(m.matches) {
- return ""
- }
- return m.matches[m.sel]
-}
-
-// View renders the query line and the match list, themed.
-func (m *Model) View() string {
- var b strings.Builder
- b.WriteString(m.input.View())
- b.WriteByte('\n')
- selStyle := lipgloss.NewStyle().Foreground(m.theme.SelFg).Background(m.theme.SelBg)
- plain := lipgloss.NewStyle().Foreground(m.theme.Text)
- pointer := lipgloss.NewStyle().Foreground(m.theme.Pointer)
- rows := m.height - 2
- if rows < 1 {
- rows = 1
- }
- for i := 0; i < len(m.matches) && i < rows; i++ {
- label := m.label(m.matches[i])
- if i == m.sel {
- b.WriteString(pointer.Render("▸ "))
- b.WriteString(selStyle.Render(label))
- } else {
- b.WriteString(plain.Render(" " + label))
- }
- b.WriteByte('\n')
- }
- return b.String()
-}
-
-// walkMarkdown returns .md files (with mtimes) under root, skipping dot-dirs.
-func walkMarkdown(root string) ([]fileEntry, error) {
- var out []fileEntry
- err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return nil // skip unreadable entries
- }
- if d.IsDir() {
- if path != root && strings.HasPrefix(d.Name(), ".") {
- return filepath.SkipDir
- }
- return nil
- }
- if strings.EqualFold(filepath.Ext(d.Name()), ".md") {
- abs, aerr := filepath.Abs(path)
- if aerr != nil {
- return nil
- }
- var mod time.Time
- if info, ierr := d.Info(); ierr == nil {
- mod = info.ModTime()
- }
- out = append(out, fileEntry{path: abs, mod: mod})
- }
- return nil
- })
- return out, err
-}
-
-// fuzzyMatch reports whether query is a case-insensitive subsequence of
-// candidate, scoring contiguous matches higher (fewer gaps -> higher score).
-func fuzzyMatch(query, candidate string) (int, bool) {
- if query == "" {
- return 0, true
- }
- q := []rune(strings.ToLower(query))
- c := []rune(strings.ToLower(candidate))
- score, qi, last := 0, 0, -1
- for ci := 0; ci < len(c) && qi < len(q); ci++ {
- if c[ci] == q[qi] {
- if last >= 0 {
- score -= ci - last - 1 // penalize gaps
- }
- last = ci
- qi++
- }
- }
- if qi != len(q) {
- return 0, false
- }
- return score, true
-}
-```
-
-> NOTE: `rankEntries` matches against `filepath.Base(e.path)` (the filename) for stable, root-independent tests; the displayed `label` remains the vault-relative path. This matches v1 behavior closely enough (filenames are the dominant signal) and keeps `rankEntries` pure.
-
-- [ ] **Step 4: Update `app.go` to pass theme + today path, and repaint picker on cycle**
-
-In `internal/app/app.go`, change `openPicker` to pass the theme and today's daily path:
-```go
-func (a *App) openPicker() (tea.Model, tea.Cmd) {
- p, err := picker.New(a.cfg.VaultDir, a.theme, a.cfg.DailyPath(time.Now()))
- if err != nil {
- a.status = "Picker failed: " + err.Error()
- return a, nil
- }
- p.SetSize(a.width, a.height-1)
- a.picker = p
- a.mode = ModePicker
- return a, nil
-}
-```
-And re-add the picker repaint to `cycleTheme` (now that `SetTheme` exists; `SetStyle` is added in Task 6 — until then only `SetTheme`):
-```go
-func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
- a.theme = theme.Next(a.theme.Name)
- a.editor.SetTheme(a.theme)
- a.preview.SetStyle(a.glamourStyle())
- if a.picker != nil {
- a.picker.SetTheme(a.theme)
- }
- a.status = "Theme: " + a.theme.Name
- return a, nil
-}
-```
-
-- [ ] **Step 5: Run picker + app + whole suite**
-
-Run: `go test ./internal/picker/ ./internal/app/`
-Expected: PASS.
-
-Run: `go test ./...`
-Expected: PASS.
-
-- [ ] **Step 6: Vet and commit**
-
-```bash
-go vet ./...
-git add internal/picker/ internal/app/
-git commit -m "feat: picker sorts by mtime, floats today's daily, themed list"
-```
-
----
-
-## Task 6: Picker glamour preview pane
-
-**Files:**
-- Modify: `internal/picker/picker.go`, `internal/picker/picker_test.go`
-- Modify: `internal/app/app.go` (pass glamour style into `picker.New`; add `SetStyle` to cycle)
-
-**Interfaces:**
-- Consumes: `preview.New`, `(*preview.Model).SetSize/SetStyle/Render/View` (Tasks 4 + existing).
-- Produces:
- - `picker.New(root string, th theme.Theme, todayPath, glamourStyle string) (*Model, error)` (signature gains `glamourStyle`).
- - `(*Model).SetStyle(s string)`.
- - Split View: list left, rounded-bordered glamour preview right.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to `internal/picker/picker_test.go`:
-```go
-func TestPickerPreviewRendersSelectedFile(t *testing.T) {
- root := t.TempDir()
- p := filepath.Join(root, "note.md")
- os.WriteFile(p, []byte("# Heading\n\nbody text"), 0o644)
-
- m, err := New(root, theme.FlexokiDark(), "", "dark")
- if err != nil {
- t.Fatal(err)
- }
- m.SetSize(120, 30)
- m.recompute() // selects note.md
- view := m.View()
- if !strings.Contains(view, "Heading") {
- t.Errorf("preview pane should render the selected file's heading; view:\n%s", view)
- }
-}
-```
-Add `"glint/internal/theme"` to the test imports if not already present.
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/picker/ -run TestPickerPreview`
-Expected: FAIL — `New` takes 3 args, not 4; no preview rendering.
-
-- [ ] **Step 3: Add the preview pane to `picker.go`**
-
-In `internal/picker/picker.go`, add the import:
-```go
- "glint/internal/preview"
-```
-Add fields to `Model` (after `theme`):
-```go
- preview *preview.Model
- style string
-```
-Change `New` to accept `glamourStyle` and build a preview model:
-```go
-func New(root string, th theme.Theme, todayPath, glamourStyle string) (*Model, error) {
- files, err := walkMarkdown(root)
- if err != nil {
- return nil, err
- }
- ti := textinput.New()
- ti.Prompt = "note › "
- ti.Placeholder = "filter…"
- ti.Focus()
- m := &Model{
- input: ti,
- all: files,
- root: root,
- todayPath: todayPath,
- width: 80,
- height: 24,
- theme: th,
- preview: preview.New(glamourStyle),
- style: glamourStyle,
- }
- m.recompute()
- return m, nil
-}
-```
-Add `SetStyle` and update `SetSize`/`SetTheme`/`recompute` to size and refresh the preview. Replace `SetSize`, add `SetStyle`, and update `recompute` to call `renderPreview`:
-```go
-// SetSize records dimensions and sizes the preview pane.
-func (m *Model) SetSize(w, h int) {
- m.width = w
- m.height = h
- m.preview.SetSize(m.previewWidth(), h-2)
-}
-
-// SetStyle changes the preview's glamour style.
-func (m *Model) SetStyle(s string) {
- m.style = s
- m.preview.SetStyle(s)
- m.renderPreview()
-}
-
-// previewWidth is the column width of the preview pane (~60%), or 0 when the
-// terminal is too narrow to split.
-func (m *Model) previewWidth() int {
- if m.width < 60 {
- return 0
- }
- return m.width*6/10 - 2 // minus border
-}
-
-// renderPreview loads the highlighted file into the preview viewport.
-func (m *Model) renderPreview() {
- if m.previewWidth() <= 0 {
- return
- }
- sel := m.Selected()
- if sel == "" {
- _ = m.preview.Render("")
- return
- }
- data, err := os.ReadFile(sel)
- if err != nil {
- _ = m.preview.Render("_could not read file_")
- return
- }
- _ = m.preview.Render(string(data))
-}
-```
-Update `recompute` to refresh the preview after ranking:
-```go
-func (m *Model) recompute() {
- m.matches = rankEntries(m.all, m.input.Value(), m.todayPath)
- if m.sel >= len(m.matches) {
- m.sel = 0
- }
- m.renderPreview()
-}
-```
-Update `Update` so moving the selection refreshes the preview — in the `KeyUp`/`KeyDown` cases call `m.renderPreview()` before returning:
-```go
- case tea.KeyUp:
- if m.sel > 0 {
- m.sel--
- m.renderPreview()
- }
- return nil
- case tea.KeyDown:
- if m.sel < len(m.matches)-1 {
- m.sel++
- m.renderPreview()
- }
- return nil
-```
-Add `"os"` to the imports. Then rewrite `View` to split list + preview:
-```go
-// View renders the query + themed match list on the left and a glamour preview
-// of the highlighted file on the right (when the terminal is wide enough).
-func (m *Model) View() string {
- left := m.listView()
- if m.previewWidth() <= 0 {
- return left
- }
- border := lipgloss.NewStyle().
- Border(lipgloss.RoundedBorder()).
- BorderForeground(m.theme.Muted).
- Width(m.previewWidth()).
- Height(m.height - 2)
- right := border.Render(m.preview.View())
- listCol := lipgloss.NewStyle().Width(m.width - m.previewWidth() - 3).Render(left)
- return lipgloss.JoinHorizontal(lipgloss.Top, listCol, right)
-}
-
-// listView is the query line plus the themed match list.
-func (m *Model) listView() string {
- var b strings.Builder
- b.WriteString(m.input.View())
- b.WriteByte('\n')
- selStyle := lipgloss.NewStyle().Foreground(m.theme.SelFg).Background(m.theme.SelBg)
- plain := lipgloss.NewStyle().Foreground(m.theme.Text)
- pointer := lipgloss.NewStyle().Foreground(m.theme.Pointer)
- rows := m.height - 2
- if rows < 1 {
- rows = 1
- }
- for i := 0; i < len(m.matches) && i < rows; i++ {
- label := m.label(m.matches[i])
- if i == m.sel {
- b.WriteString(pointer.Render("▸ "))
- b.WriteString(selStyle.Render(label))
- } else {
- b.WriteString(plain.Render(" " + label))
- }
- b.WriteByte('\n')
- }
- return b.String()
-}
-```
-(Delete the old `View` that this replaces.)
-
-- [ ] **Step 4: Update `app.go` to pass the glamour style and repaint preview on cycle**
-
-In `openPicker`, pass the glamour style:
-```go
- p, err := picker.New(a.cfg.VaultDir, a.theme, a.cfg.DailyPath(time.Now()), a.glamourStyle())
-```
-In `cycleTheme`, add the picker `SetStyle` call:
-```go
- if a.picker != nil {
- a.picker.SetTheme(a.theme)
- a.picker.SetStyle(a.glamourStyle())
- }
-```
-
-- [ ] **Step 5: Run picker + app + whole suite**
-
-Run: `go test ./internal/picker/ ./internal/app/`
-Expected: PASS.
-
-Run: `go test ./...`
-Expected: PASS.
-
-- [ ] **Step 6: Vet and commit**
-
-```bash
-go vet ./...
-git add internal/picker/ internal/app/
-git commit -m "feat: live glamour preview pane in the picker"
-```
-
----
-
-## Task 7: Picker `Ctrl+N` new note
-
-**Files:**
-- Modify: `internal/picker/picker.go`, `internal/picker/picker_test.go`
-- Modify: `internal/app/app.go`, `internal/app/app_test.go`
-
-**Interfaces:**
-- Consumes: `(*picker.Model).Query` (Task 5).
-- Produces:
- - `picker.NewNotePath(root, query string) string` (pure, exported, tested).
- - App: `Ctrl+N` in `ModePicker` creates the note and opens it.
-
-- [ ] **Step 1: Write the failing picker test**
-
-Append to `internal/picker/picker_test.go`:
-```go
-func TestNewNotePath(t *testing.T) {
- root := "/v"
- cases := map[string]string{
- "foo": filepath.Join("/v", "foo.md"),
- "Folder/Bar": filepath.Join("/v", "Folder", "Bar.md"),
- "x.md": filepath.Join("/v", "x.md"),
- " spaced ": filepath.Join("/v", "spaced.md"),
- }
- for q, want := range cases {
- if got := NewNotePath(root, q); got != want {
- t.Errorf("NewNotePath(%q) = %q, want %q", q, got, want)
- }
- }
- if NewNotePath(root, " ") != "" {
- t.Error("blank query should yield empty path")
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/picker/ -run TestNewNotePath`
-Expected: FAIL — `undefined: NewNotePath`.
-
-- [ ] **Step 3: Implement `NewNotePath`**
-
-Add to `internal/picker/picker.go` (near the bottom):
-```go
-// NewNotePath builds an absolute note path from a query under root. It trims
-// surrounding whitespace, appends ".md" when absent, and supports "Folder/Name".
-// A blank query yields "".
-func NewNotePath(root, query string) string {
- rel := strings.TrimSpace(query)
- if rel == "" {
- return ""
- }
- if !strings.EqualFold(filepath.Ext(rel), ".md") {
- rel += ".md"
- }
- return filepath.Join(root, rel)
-}
-```
-
-- [ ] **Step 4: Run picker tests**
-
-Run: `go test ./internal/picker/`
-Expected: PASS.
-
-- [ ] **Step 5: Write the failing app test**
-
-Append to `internal/app/app_test.go`:
-```go
-func TestCtrlNCreatesNoteFromQuery(t *testing.T) {
- dir := t.TempDir()
- cfg := config.Default()
- cfg.VaultDir = dir
- a := New(cfg)
- a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) // open picker
- if a.mode != ModePicker {
- t.Fatalf("expected picker mode")
- }
- // Type a name into the picker query.
- a.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("ideas")})
- a.Update(tea.KeyMsg{Type: tea.KeyCtrlN})
-
- if a.mode != ModeEditor {
- t.Errorf("Ctrl+N should open the new note in the editor, mode = %d", a.mode)
- }
- want := filepath.Join(dir, "ideas.md")
- if a.path != want {
- t.Errorf("a.path = %q, want %q", a.path, want)
- }
- if _, err := os.Stat(want); err != nil {
- t.Errorf("new note should exist on disk: %v", err)
- }
-}
-```
-
-- [ ] **Step 6: Run to verify it fails**
-
-Run: `go test ./internal/app/ -run TestCtrlNCreatesNoteFromQuery`
-Expected: FAIL — `Ctrl+N` is unhandled; no file created.
-
-- [ ] **Step 7: Wire `Ctrl+N` in the app's picker routing**
-
-In `internal/app/app.go`, change the `ModePicker` branch of the mode switch to handle `Ctrl+N`:
-```go
- case ModePicker:
- switch msg.Type {
- case tea.KeyEnter:
- if sel := a.picker.Selected(); sel != "" {
- if err := a.Load(sel); err != nil {
- a.status = "Open failed: " + err.Error()
- }
- }
- return a, nil
- case tea.KeyCtrlN:
- return a.newNote()
- }
- return a, a.picker.Update(msg)
-```
-Add the `newNote` helper (near `openDaily`):
-```go
-// newNote creates a note named after the picker query and opens it.
-func (a *App) newNote() (tea.Model, tea.Cmd) {
- p := picker.NewNotePath(a.cfg.VaultDir, a.picker.Query())
- if p == "" {
- a.status = "Type a name first"
- return a, nil
- }
- if _, err := os.Stat(p); os.IsNotExist(err) {
- if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
- a.status = "New note dir failed: " + err.Error()
- return a, nil
- }
- if err := os.WriteFile(p, []byte{}, 0o644); err != nil {
- a.status = "New note failed: " + err.Error()
- return a, nil
- }
- }
- if err := a.Load(p); err != nil {
- a.status = "Open failed: " + err.Error()
- }
- return a, nil
-}
-```
-
-- [ ] **Step 8: Run app + whole suite, vet, build**
-
-Run: `go test ./...`
-Expected: PASS.
-
-Run: `go vet ./... && go build ./...`
-Expected: clean, builds.
-
-- [ ] **Step 9: Commit**
-
-```bash
-git add internal/picker/ internal/app/
-git commit -m "feat: Ctrl+N creates a note from the picker query"
-```
-
-- [ ] **Step 10: Manual smoke (user-driven, real terminal)**
-
-```bash
-go run . README.md # editor — themed; toggle Ctrl+T (light/dark/charm)
-go run . # picker — mtime order, today on top, preview pane, Ctrl+N
-```
-Expected: readable text in a light terminal under flexoki-light; `Ctrl+T` cycles light → dark → charm; YAML frontmatter shows colored keys/values with `---` muted; picker lists newest-first with today's daily on top, a glamour preview pane on the right, and `Ctrl+N` creates a note from the typed name.
-
----
-
-## Self-Review Notes
-
-**Spec coverage:**
-- A.1 theme package extraction → Task 1 (+ Task 2 migrates editor off `editor.Theme`).
-- A.2 Theme struct (markdown + UI fields, Name, GlamourStyle) → Task 1.
-- A.3 three palettes with concrete hexes → Task 1 `themes.go`.
-- A.4 ByName/Detect/Resolve, macOS detection + non-darwin fallback → Task 1.
-- A.5 config `theme` key default auto; `glamour_style` default "" overrides theme → Task 4.
-- A.6 `Ctrl+T` cycle; editor/status/picker/glamour repaint → Tasks 4 (editor/status/glamour) + 5/6 (picker).
-- B.1 mtime sort + today-float + fuzzy+mtime tiebreak → Task 5 (`rankEntries`).
-- B.2 split preview pane (glamour, theme style, rounded border, updates on move) → Task 6.
-- B.3 `Ctrl+N` new note from query (Folder/Name, .md append, mkdir, open-if-exists) → Task 7.
-- B.4 full-text mode out → not implemented (intentional).
-- C structure/tests → each task is TDD; detection parse is deterministic (`detectFrom`); per-theme all-colors test in Task 1.
-- D YAML frontmatter highlighting (keys/values/markers/comments, char-for-char) → Task 3.
-
-**Type consistency:** `theme.Theme` field names (`Text, Heading, Code, Link, Wikilink, ListMarker, Blockquote, Accent, Background, Muted, StatusFg, StatusBg, SelFg, SelBg, Pointer, Name, GlamourStyle`) are used identically in editor (Tasks 2–3), app (Task 4), and picker (Tasks 5–6). `picker.New` signature grows once in Task 5 (`+th, +todayPath`) and once in Task 6 (`+glamourStyle`); `openPicker` is updated in the same tasks. `cycleTheme` is introduced in Task 4 without the picker block, then the picker repaint lines are added in Tasks 5 (`SetTheme`) and 6 (`SetStyle`) — each task leaves the tree compiling.
-
-**Known follow-ups (not v1.1 blockers):** `rankEntries` matches on filename (`filepath.Base`) rather than the vault-relative label; preview re-renders the file on every selection move (no caching); charm hexes target the brand aesthetic and can be tuned.
docs/superpowers/plans/2026-06-28-glint-writing-canvas.md +0 −833
@@ -1,838 +0,0 @@
-# glint v1.2 — Writing Canvas Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Give the editor an iA Writer–style writing canvas: a centered, percentage-width text column with left/right margins and a little top air, text left-aligned inside it, long paragraphs soft-wrapping at the column edge, and the glamour preview sharing the same column.
-
-**Architecture:** Soft-wrapping is a display-only layer in the `editor` package: logical lines and the logical cursor are unchanged; rendering and vertical navigation become *visual-row* aware. A new `wrap.go` provides word-aware line wrapping, span slicing, and a visual-row builder. The `app` owns layout — it sizes the editor and preview to a computed `contentWidth` and indents their output by a left margin plus a top pad. The picker keeps its full-width split.
-
-**Tech Stack:** Go 1.26, Bubbletea, Bubbles (viewport), Lipgloss, Glamour — already in go.mod.
-
-**Prerequisite:** Build v1.1 (`docs/superpowers/plans/2026-06-28-glint-theme-picker.md`) FIRST. This plan assumes the editor already consumes `theme.Theme` and has `SetTheme`, the app holds an active `theme.Theme` (`a.theme`), and the picker is themed. Do not start this plan until v1.1 is merged.
-
-## Global Constraints
-
-- Module path `glint`; internal packages import as `glint/internal/<pkg>`.
-- **Dependency policy:** newest resolver-selected versions; do not pin or flag versions.
-- **Explicit-foreground invariant:** every rendered span keeps an explicit theme foreground. `sliceSpans` preserves the style of every span it slices — it never emits an unstyled span.
-- **Markup-visible invariant:** soft-wrapping is display-only. The logical buffer is never modified by wrapping; `Bytes()` round-trips the exact logical lines; markup characters stay visible in every visual row.
-- **Layout is rendering-only:** centering margins and top padding are added to the rendered frame, never to the buffer. Saving never inserts margin spaces or wrap breaks.
-- **Wrap partition guarantee:** `wrapLine` segments partition a line's runes contiguously — `concat(segment texts) == line`, no dropped or duplicated runes (the breaking space stays as the trailing rune of its segment).
-- Canvas constants: column ratio `0.65`, max `100`, min `24`, top pad `1`. Column width `= clamp(round(width × 0.65), 24, 100)`, further clamped `≤ width`. Left margin `= (width − contentWidth) / 2`. These are constants — no config keys.
-- Vertical nav: Up/Down move by **visual** row keeping a goal column; Left/Right and Home/End stay **logical**. Scroll is a **visual-row** index.
-- Scope: editor + preview get the canvas; the picker does not. Cursor is a themed cell (no thin-bar). No visual Home/End. No measure config.
-- TDD per task: failing test → run (fails) → implement → run (passes) → commit. Each task ends `go vet ./...` clean and full `go test ./...` green.
-
----
-
-## File Structure
-
-```
-internal/editor/
- wrap.go NEW: segment, wrapLine, sliceSpans, vrow, buildVisual, cursorVIndex
- wrap_test.go NEW: wrap (word/hard/empty/multibyte/partition); sliceSpans boundaries
- editor.go MOD: goalCol field; visual View; visual MoveUp/MoveDown + applyGoal;
- visual followCursor; setGoal/visualColOf; setGoal in edit/horizontal ops;
- themed cursor; SetContent resets goalCol
- editor_test.go MOD: add visual-wrap nav tests + Bytes round-trip-under-wrap (existing tests stay)
-internal/app/
- app.go MOD: canvas constants; contentWidth/leftMargin/topPad; setSize sizes
- editor+preview to contentWidth; View indents+pads editor & preview; picker unindented
- app_test.go MOD: contentWidth/leftMargin math tests
-```
-
----
-
-## Task 1: Wrapping utilities (`wrap.go`)
-
-**Files:**
-- Create: `internal/editor/wrap.go`
-- Test: `internal/editor/wrap_test.go`
-
-**Interfaces:**
-- Consumes: `Span` (existing), `ScanLines`, `theme.Theme` (v1.1).
-- Produces:
- - `segment struct { text string; start int }` (unexported).
- - `wrapLine(line string, width int) []segment`.
- - `sliceSpans(spans []Span, start, end int) []Span`.
- - `vrow struct { logRow, start, runes int; spans []Span }` (unexported).
- - `(*Editor).buildVisual() []vrow`.
- - `cursorVIndex(rows []vrow, cur Position) int`.
-
-- [ ] **Step 1: Write the failing tests**
-
-Create `internal/editor/wrap_test.go`:
-```go
-package editor
-
-import (
- "testing"
-
- "glint/internal/theme"
-
- "github.com/charmbracelet/lipgloss"
-)
-
-func segText(segs []segment) string {
- s := ""
- for _, sg := range segs {
- s += sg.text
- }
- return s
-}
-
-func TestWrapLineFitsReturnsOneSegment(t *testing.T) {
- segs := wrapLine("short line", 80)
- if len(segs) != 1 || segs[0].text != "short line" || segs[0].start != 0 {
- t.Fatalf("segs = %#v", segs)
- }
-}
-
-func TestWrapLineEmpty(t *testing.T) {
- segs := wrapLine("", 80)
- if len(segs) != 1 || segs[0].text != "" || segs[0].start != 0 {
- t.Fatalf("empty line segs = %#v", segs)
- }
-}
-
-func TestWrapLineWordBreakPartition(t *testing.T) {
- line := "aaaa bbbb cccc"
- segs := wrapLine(line, 9)
- if segText(segs) != line {
- t.Errorf("partition broken: %q != %q", segText(segs), line)
- }
- if len(segs) != 2 {
- t.Fatalf("want 2 segments, got %d: %#v", len(segs), segs)
- }
- if segs[0].text != "aaaa " || segs[0].start != 0 {
- t.Errorf("seg0 = %#v", segs[0])
- }
- if segs[1].text != "bbbb cccc" || segs[1].start != 5 {
- t.Errorf("seg1 = %#v", segs[1])
- }
-}
-
-func TestWrapLineHardBreaksLongWord(t *testing.T) {
- segs := wrapLine("abcdefghij", 4)
- if segText(segs) != "abcdefghij" {
- t.Errorf("partition broken: %q", segText(segs))
- }
- want := []segment{{"abcd", 0}, {"efgh", 4}, {"ij", 8}}
- if len(segs) != len(want) {
- t.Fatalf("got %d segments, want %d", len(segs), len(want))
- }
- for i := range want {
- if segs[i] != want[i] {
- t.Errorf("seg[%d] = %#v, want %#v", i, segs[i], want[i])
- }
- }
-}
-
-func TestWrapLineMultibytePartition(t *testing.T) {
- line := "héllo wörld café"
- segs := wrapLine(line, 7)
- if segText(segs) != line {
- t.Errorf("multibyte partition broken: %q != %q", segText(segs), line)
- }
-}
-
-func TestSliceSpansAcrossBoundary(t *testing.T) {
- red := lipgloss.NewStyle().Foreground(lipgloss.Color("#ff0000"))
- blue := lipgloss.NewStyle().Foreground(lipgloss.Color("#0000ff"))
- spans := []Span{{Text: "abc", Style: red}, {Text: "def", Style: blue}}
- out := sliceSpans(spans, 2, 5) // "c" (red) + "de" (blue)
- got := ""
- for _, sp := range out {
- got += sp.Text
- }
- if got != "cde" {
- t.Errorf("sliced text = %q, want cde", got)
- }
- if len(out) != 2 || out[0].Style.GetForeground() != lipgloss.Color("#ff0000") ||
- out[1].Style.GetForeground() != lipgloss.Color("#0000ff") {
- t.Errorf("styles not preserved: %#v", out)
- }
-}
-
-func TestBuildVisualAndCursorIndex(t *testing.T) {
- e := New()
- e.SetTheme(theme.FlexokiDark())
- e.Lines = []string{"aaaa bbbb cccc", "x"}
- e.Width = 9
- rows := e.buildVisual()
- // line 0 wraps into 2 visual rows, line 1 is 1 → 3 total.
- if len(rows) != 3 {
- t.Fatalf("visual rows = %d, want 3", len(rows))
- }
- // cursor at end of seg2 of line 0 maps to the second visual row.
- if got := cursorVIndex(rows, Position{Row: 0, Col: 10}); got != 1 {
- t.Errorf("cursorVIndex = %d, want 1", got)
- }
- // cursor on line 1 maps to row index 2.
- if got := cursorVIndex(rows, Position{Row: 1, Col: 0}); got != 2 {
- t.Errorf("cursorVIndex(line1) = %d, want 2", got)
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/editor/ -run 'TestWrap|TestSliceSpans|TestBuildVisual'`
-Expected: FAIL — `undefined: wrapLine`, `undefined: sliceSpans`, `undefined: buildVisual`.
-
-- [ ] **Step 3: Implement `wrap.go`**
-
-Create `internal/editor/wrap.go`:
-```go
-package editor
-
-// segment is one visual row of a logical line: a contiguous rune slice plus the
-// rune offset (start column) within the logical line where it begins.
-type segment struct {
- text string
- start int
-}
-
-// wrapLine word-wraps a logical line into visual segments at the given width.
-// It breaks just after the last space that fits; a word longer than width is
-// hard-broken at width. The segments partition the line's runes contiguously
-// (concatenating their text reproduces the line exactly), so the cursor maps to
-// exactly one segment. A width <= 0 or a line that fits returns one segment; an
-// empty line returns one empty segment.
-func wrapLine(line string, width int) []segment {
- r := []rune(line)
- if width <= 0 || len(r) <= width {
- return []segment{{text: line, start: 0}}
- }
- var segs []segment
- start := 0
- for start < len(r) {
- if start+width >= len(r) {
- segs = append(segs, segment{text: string(r[start:]), start: start})
- break
- }
- end := start + width
- brk := -1
- for i := end - 1; i > start; i-- {
- if r[i] == ' ' {
- brk = i + 1 // keep the space as this segment's trailing rune
- break
- }
- }
- if brk <= start {
- brk = end // long word: hard break
- }
- segs = append(segs, segment{text: string(r[start:brk]), start: start})
- start = brk
- }
- if len(segs) == 0 {
- segs = append(segs, segment{text: "", start: 0})
- }
- return segs
-}
-
-// sliceSpans returns the spans covering rune range [start, end) of a line whose
-// spans concatenate to the full line. Boundary spans are split; styles are
-// preserved.
-func sliceSpans(spans []Span, start, end int) []Span {
- var out []Span
- pos := 0
- for _, sp := range spans {
- r := []rune(sp.Text)
- spStart, spEnd := pos, pos+len(r)
- pos = spEnd
- lo := max(spStart, start)
- hi := min(spEnd, end)
- if lo < hi {
- out = append(out, Span{Text: string(r[lo-spStart : hi-spStart]), Style: sp.Style})
- }
- }
- return out
-}
-
-// vrow is a rendered visual row: which logical row it came from, the rune start
-// offset and rune count within that line, and the styled spans for the segment.
-type vrow struct {
- logRow int
- start int
- runes int
- spans []Span
-}
-
-// buildVisual wraps every logical line into visual rows, slicing each line's
-// styled spans to the segment ranges.
-func (e *Editor) buildVisual() []vrow {
- all := ScanLines(e.Lines, e.theme)
- var rows []vrow
- for li := range e.Lines {
- for _, s := range wrapLine(e.Lines[li], e.Width) {
- n := len([]rune(s.text))
- rows = append(rows, vrow{
- logRow: li,
- start: s.start,
- runes: n,
- spans: sliceSpans(all[li], s.start, s.start+n),
- })
- }
- }
- return rows
-}
-
-// cursorVIndex returns the index of the visual row holding the cursor. A cursor
-// at the end of a line (or on an empty line) maps to that line's last segment.
-func cursorVIndex(rows []vrow, cur Position) int {
- last := -1
- for i, vr := range rows {
- if vr.logRow != cur.Row {
- continue
- }
- last = i
- if cur.Col >= vr.start && cur.Col < vr.start+vr.runes {
- return i
- }
- }
- return last
-}
-```
-
-- [ ] **Step 4: Run to verify it passes**
-
-Run: `go test ./internal/editor/ -run 'TestWrap|TestSliceSpans|TestBuildVisual'`
-Expected: PASS.
-
-- [ ] **Step 5: Vet and commit**
-
-```bash
-go vet ./internal/editor/
-git add internal/editor/wrap.go internal/editor/wrap_test.go
-git commit -m "feat: word-aware line wrapping + span slicing + visual rows"
-```
-
----
-
-## Task 2: Editor visual rendering and navigation
-
-**Files:**
-- Modify: `internal/editor/editor.go`
-- Modify: `internal/editor/editor_test.go`
-
-**Interfaces:**
-- Consumes: `wrapLine`, `buildVisual`, `cursorVIndex`, `sliceSpans` (Task 1).
-- Produces:
- - `Editor` gains an unexported `goalCol int`.
- - `View()` renders visual rows with a themed cursor cell.
- - `MoveUp`/`MoveDown` move by visual row with a preserved goal column.
- - `Scroll` is a visual-row index; `followCursor` scrolls by visual row.
- - Horizontal/edit ops set the goal column.
-
-- [ ] **Step 1: Write the failing tests**
-
-Append to `internal/editor/editor_test.go`:
-```go
-func TestVisualDownAndUpAcrossWrappedLine(t *testing.T) {
- e := New()
- e.Lines = []string{"aaaa bbbb cccc"} // wraps at width 9 into ["aaaa ","bbbb cccc"]
- e.SetSize(9, 10)
- e.Cursor = Position{Row: 0, Col: 0}
- e.MoveDown() // to the second visual row, goal column 0
- if e.Cursor != (Position{Row: 0, Col: 5}) {
- t.Errorf("after MoveDown: %+v, want {0 5}", e.Cursor)
- }
- e.MoveUp() // back to the first visual row, goal column 0
- if e.Cursor != (Position{Row: 0, Col: 0}) {
- t.Errorf("after MoveUp: %+v, want {0 0}", e.Cursor)
- }
-}
-
-func TestVisualDownKeepsGoalColumn(t *testing.T) {
- e := New()
- e.Lines = []string{"aaaa bbbb cccc"}
- e.SetSize(9, 10)
- e.Cursor = Position{Row: 0, Col: 2} // visual column 2 in segment 0
- e.MoveDown() // segment 1 starts at col 5 → col 5+2 = 7
- if e.Cursor != (Position{Row: 0, Col: 7}) {
- t.Errorf("after MoveDown with goal: %+v, want {0 7}", e.Cursor)
- }
-}
-
-func TestBytesRoundTripUnaffectedByWrap(t *testing.T) {
- e := New()
- e.SetContent([]byte("a very long single logical line that will wrap many times\nsecond"))
- e.SetSize(10, 5)
- if string(e.Bytes()) != "a very long single logical line that will wrap many times\nsecond" {
- t.Errorf("wrap altered the buffer: %q", string(e.Bytes()))
- }
-}
-
-func TestScrollIsVisualRowIndex(t *testing.T) {
- e := New()
- e.Lines = []string{"aaaa bbbb cccc dddd eeee ffff"} // one logical line, many visual rows at width 9
- e.SetSize(9, 2) // only 2 visible visual rows
- e.Cursor = Position{Row: 0, Col: 0}
- // Move down several visual rows; Scroll must follow so the cursor stays visible.
- for i := 0; i < 3; i++ {
- e.MoveDown()
- }
- rows := e.buildVisual()
- ci := cursorVIndex(rows, e.Cursor)
- if ci < e.Scroll || ci >= e.Scroll+e.Height {
- t.Errorf("cursor visual row %d not in viewport [%d,%d)", ci, e.Scroll, e.Scroll+e.Height)
- }
-}
-```
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/editor/ -run 'TestVisual|TestBytesRoundTripUnaffected|TestScrollIsVisual'`
-Expected: FAIL — `MoveDown` still moves logical rows; `e.goalCol` undefined.
-
-- [ ] **Step 3: Add the `goalCol` field and reset it in `SetContent`**
-
-In `internal/editor/editor.go`, add the field to the `Editor` struct (after `Height int`):
-```go
- goalCol int // remembered visual column for vertical moves
-```
-In `SetContent`, reset it (add after `e.Scroll = 0`):
-```go
- e.goalCol = 0
-```
-
-- [ ] **Step 4: Replace `View` with the visual renderer**
-
-Replace the existing `View` method with:
-```go
-// View renders the visible visual rows, styled, with a themed cursor cell on
-// the cursor's visual row. Output is e.Width columns wide; the app adds margins.
-func (e *Editor) View() string {
- cursorStyle := lipgloss.NewStyle().Foreground(e.theme.Background).Background(e.theme.Pointer)
- rows := e.buildVisual()
- ci := cursorVIndex(rows, e.Cursor)
- var b strings.Builder
- end := e.Scroll + e.Height
- if end > len(rows) {
- end = len(rows)
- }
- for r := e.Scroll; r < end; r++ {
- if r == ci {
- b.WriteString(renderSpansCursor(rows[r].spans, e.Cursor.Col-rows[r].start, cursorStyle))
- } else {
- b.WriteString(renderSpans(rows[r].spans))
- }
- b.WriteByte('\n')
- }
- for r := end; r < e.Scroll+e.Height; r++ {
- b.WriteByte('\n')
- }
- return b.String()
-}
-```
-
-- [ ] **Step 5: Replace `followCursor` with the visual version and add goal helpers**
-
-Replace the existing `followCursor` method with:
-```go
-// followCursor scrolls the viewport so the cursor's visual row stays visible.
-func (e *Editor) followCursor() {
- rows := e.buildVisual()
- ci := cursorVIndex(rows, e.Cursor)
- if ci < 0 {
- e.Scroll = 0
- return
- }
- if ci < e.Scroll {
- e.Scroll = ci
- }
- if ci >= e.Scroll+e.Height {
- e.Scroll = ci - e.Height + 1
- }
- if e.Scroll < 0 {
- e.Scroll = 0
- }
-}
-
-// setGoal records the cursor's current visual column as the goal for vertical moves.
-func (e *Editor) setGoal() { e.goalCol = e.visualColOf(e.Cursor.Row, e.Cursor.Col) }
-
-// visualColOf returns the column of (row, col) within its visual segment.
-func (e *Editor) visualColOf(row, col int) int {
- segs := wrapLine(e.Lines[row], e.Width)
- for i := len(segs) - 1; i >= 0; i-- {
- if col >= segs[i].start {
- return col - segs[i].start
- }
- }
- return col
-}
-```
-
-- [ ] **Step 6: Replace `MoveUp`/`MoveDown` with visual moves and add `applyGoal`**
-
-Replace the existing `MoveUp` and `MoveDown` methods with:
-```go
-// MoveUp moves to the previous visual row, keeping the goal column.
-func (e *Editor) MoveUp() {
- rows := e.buildVisual()
- ci := cursorVIndex(rows, e.Cursor)
- if ci <= 0 {
- return
- }
- e.applyGoal(rows[ci-1])
- e.followCursor()
-}
-
-// MoveDown moves to the next visual row, keeping the goal column.
-func (e *Editor) MoveDown() {
- rows := e.buildVisual()
- ci := cursorVIndex(rows, e.Cursor)
- if ci < 0 || ci+1 >= len(rows) {
- return
- }
- e.applyGoal(rows[ci+1])
- e.followCursor()
-}
-
-// applyGoal places the cursor at the goal column on the given visual row.
-func (e *Editor) applyGoal(target vrow) {
- e.Cursor.Row = target.logRow
- e.Cursor.Col = target.start + min(e.goalCol, target.runes)
-}
-```
-
-- [ ] **Step 7: Set the goal column in horizontal and edit ops**
-
-In `internal/editor/editor.go`, add `e.setGoal()` (and `e.followCursor()` where missing) so wrapping and scrolling stay correct. Make these exact edits:
-
-`MoveLeft` — add `e.setGoal()` before the existing `e.followCursor()`:
-```go
-func (e *Editor) MoveLeft() {
- if e.Cursor.Col > 0 {
- e.Cursor.Col--
- } else if e.Cursor.Row > 0 {
- e.Cursor.Row--
- e.Cursor.Col = len([]rune(e.Lines[e.Cursor.Row]))
- }
- e.setGoal()
- e.followCursor()
-}
-```
-`MoveRight` — same:
-```go
-func (e *Editor) MoveRight() {
- if e.Cursor.Col < len(e.curLine()) {
- e.Cursor.Col++
- } else if e.Cursor.Row < len(e.Lines)-1 {
- e.Cursor.Row++
- e.Cursor.Col = 0
- }
- e.setGoal()
- e.followCursor()
-}
-```
-`MoveHome`/`MoveEnd` — replace the one-liners:
-```go
-func (e *Editor) MoveHome() {
- e.Cursor.Col = 0
- e.setGoal()
- e.followCursor()
-}
-func (e *Editor) MoveEnd() {
- e.Cursor.Col = len(e.curLine())
- e.setGoal()
- e.followCursor()
-}
-```
-`InsertRune` — append `e.setGoal()` and `e.followCursor()` before the closing brace:
-```go
-func (e *Editor) InsertRune(r rune) {
- rs := e.curLine()
- col := clamp(e.Cursor.Col, 0, len(rs))
- rs = append(rs[:col], append([]rune{r}, rs[col:]...)...)
- e.setLine(rs)
- e.Cursor.Col = col + 1
- e.Dirty = true
- e.setGoal()
- e.followCursor()
-}
-```
-`InsertNewline` — add `e.setGoal()` right before the existing `e.followCursor()` at the end.
-
-`Backspace` — add `e.setGoal()` and `e.followCursor()` to the within-line branch (which currently returns early without following), and `e.setGoal()` before the existing `e.followCursor()` in the join branch:
-```go
-func (e *Editor) Backspace() {
- if e.Cursor.Col > 0 {
- rs := e.curLine()
- rs = append(rs[:e.Cursor.Col-1], rs[e.Cursor.Col:]...)
- e.setLine(rs)
- e.Cursor.Col--
- e.Dirty = true
- e.setGoal()
- e.followCursor()
- return
- }
- if e.Cursor.Row == 0 {
- return
- }
- prev := []rune(e.Lines[e.Cursor.Row-1])
- joinCol := len(prev)
- merged := string(prev) + e.Lines[e.Cursor.Row]
- e.Lines[e.Cursor.Row-1] = merged
- e.Lines = append(e.Lines[:e.Cursor.Row], e.Lines[e.Cursor.Row+1:]...)
- e.Cursor.Row--
- e.Cursor.Col = joinCol
- e.Dirty = true
- e.setGoal()
- e.followCursor()
-}
-```
-`Delete` — add `e.setGoal()` and `e.followCursor()` to the within-line branch and the join branch:
-```go
-func (e *Editor) Delete() {
- rs := e.curLine()
- if e.Cursor.Col < len(rs) {
- rs = append(rs[:e.Cursor.Col], rs[e.Cursor.Col+1:]...)
- e.setLine(rs)
- e.Dirty = true
- e.setGoal()
- e.followCursor()
- return
- }
- if e.Cursor.Row >= len(e.Lines)-1 {
- return
- }
- e.Lines[e.Cursor.Row] = e.Lines[e.Cursor.Row] + e.Lines[e.Cursor.Row+1]
- e.Lines = append(e.Lines[:e.Cursor.Row+1], e.Lines[e.Cursor.Row+2:]...)
- e.Dirty = true
- e.setGoal()
- e.followCursor()
-}
-```
-
-- [ ] **Step 8: Run the editor suite**
-
-Run: `go test ./internal/editor/`
-Expected: PASS — the new visual tests plus all v1 tests (the existing movement tests are unaffected because at width 80 the short test lines do not wrap, so visual rows coincide with logical rows).
-
-- [ ] **Step 9: Vet and commit**
-
-```bash
-go vet ./...
-git add internal/editor/editor.go internal/editor/editor_test.go
-git commit -m "feat: visual-row rendering, soft-wrap cursor and scroll in the editor"
-```
-
----
-
-## Task 3: App canvas layout (centering + padding)
-
-**Files:**
-- Modify: `internal/app/app.go`
-- Modify: `internal/app/app_test.go`
-
-**Interfaces:**
-- Consumes: `(*editor.Editor).SetSize/View`, `(*preview.Model).SetSize/View` (existing).
-- Produces:
- - Canvas constants and `(*App).contentWidth()`, `(*App).leftMargin()`, `(*App).topPad()`.
- - `setSize` sizes the editor and preview to `contentWidth`.
- - `View` indents the editor and preview by the left margin and prepends the top pad; the picker stays full-width.
-
-- [ ] **Step 1: Write the failing tests**
-
-Append to `internal/app/app_test.go`:
-```go
-func TestCanvasContentWidthCapsAndCenters(t *testing.T) {
- a := newApp()
- a.Update(tea.WindowSizeMsg{Width: 200, Height: 40})
- if cw := a.contentWidth(); cw != 100 {
- t.Errorf("contentWidth = %d, want 100 (capped)", cw)
- }
- if lm := a.leftMargin(); lm != (200-100)/2 {
- t.Errorf("leftMargin = %d, want %d", lm, (200-100)/2)
- }
-}
-
-func TestCanvasContentWidthFloorsOnNarrow(t *testing.T) {
- a := newApp()
- a.Update(tea.WindowSizeMsg{Width: 30, Height: 20})
- if cw := a.contentWidth(); cw != 24 {
- t.Errorf("contentWidth = %d, want 24 (floor)", cw)
- }
-}
-
-func TestCanvasEditorViewIsIndented(t *testing.T) {
- a := newApp()
- a.Update(tea.WindowSizeMsg{Width: 120, Height: 20})
- a.editor.SetContent([]byte("hello"))
- view := a.View()
- // The editor body sits in a centered column → at least one rendered line
- // starts with the left-margin spaces.
- if a.leftMargin() <= 0 {
- t.Fatal("expected a positive left margin at width 120")
- }
- pad := strings.Repeat(" ", a.leftMargin())
- found := false
- for _, ln := range strings.Split(view, "\n") {
- if strings.HasPrefix(ln, pad) && strings.Contains(ln, "hello") {
- found = true
- }
- }
- if !found {
- t.Errorf("editor content not indented by left margin; view:\n%s", view)
- }
-}
-```
-Add `"strings"` to the test file's imports if not already present (Task-4 of v1.1 did not require it; add it here).
-
-- [ ] **Step 2: Run to verify it fails**
-
-Run: `go test ./internal/app/ -run TestCanvas`
-Expected: FAIL — `a.contentWidth` undefined.
-
-- [ ] **Step 3: Add the import and canvas constants/helpers**
-
-In `internal/app/app.go`, add `"math"` to the import block. Add the constants near the top (after the `pendingDiscard` consts):
-```go
-// Canvas layout: a centered, percentage-width text column with a little top air.
-const (
- canvasRatio = 0.65
- canvasMax = 100
- canvasMin = 24
- canvasTopPad = 1
-)
-```
-Add the helpers (near `setSize`):
-```go
-// contentWidth is the centered text column width: ~65% of the terminal, capped
-// for readability and floored so it never collapses, never wider than the term.
-func (a *App) contentWidth() int {
- w := int(math.Round(float64(a.width) * canvasRatio))
- if w > canvasMax {
- w = canvasMax
- }
- if w < canvasMin {
- w = canvasMin
- }
- if w > a.width {
- w = a.width
- }
- return w
-}
-
-// leftMargin centers the content column in the terminal.
-func (a *App) leftMargin() int {
- m := (a.width - a.contentWidth()) / 2
- if m < 0 {
- m = 0
- }
- return m
-}
-
-func (a *App) topPad() int { return canvasTopPad }
-
-// indentLines prefixes each non-empty line with n spaces (blank rows stay blank,
-// so the trailing newline of a sub-view does not become a spaces-only row).
-func indentLines(s string, n int) string {
- if n <= 0 {
- return s
- }
- pad := strings.Repeat(" ", n)
- lines := strings.Split(s, "\n")
- for i, ln := range lines {
- if ln != "" {
- lines[i] = pad + ln
- }
- }
- return strings.Join(lines, "\n")
-}
-```
-
-- [ ] **Step 4: Size the editor and preview to the content width**
-
-Replace `setSize` with:
-```go
-func (a *App) setSize(w, h int) {
- a.width = w
- a.height = h
- cw := a.contentWidth()
- textRows := h - 1 - a.topPad() // status bar + top pad
- if textRows < 1 {
- textRows = 1
- }
- a.editor.SetSize(cw, textRows)
- a.preview.SetSize(cw, textRows)
- if a.picker != nil {
- a.picker.SetSize(w, h-1) // picker keeps its full-width split
- }
-}
-```
-
-- [ ] **Step 5: Indent and pad the editor/preview in `View`**
-
-Replace `View` with:
-```go
-// View renders the active sub-view. The editor and preview sit in a centered,
-// padded column; the picker keeps its own full-width layout.
-func (a *App) View() string {
- if a.mode == ModePicker {
- body := a.picker.View()
- if !strings.HasSuffix(body, "\n") {
- body += "\n"
- }
- return body + a.statusBar()
- }
-
- var body string
- if a.mode == ModePreview {
- body = a.preview.View()
- } else {
- body = a.editor.View()
- }
- body = indentLines(body, a.leftMargin())
- if a.topPad() > 0 {
- body = strings.Repeat("\n", a.topPad()) + body
- }
- if !strings.HasSuffix(body, "\n") {
- body += "\n"
- }
- return body + a.statusBar()
-}
-```
-
-- [ ] **Step 6: Run app + whole suite, vet, build**
-
-Run: `go test ./internal/app/`
-Expected: PASS.
-
-Run: `go vet ./... && go build ./... && go test ./...`
-Expected: clean, builds, all pass.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add internal/app/
-git commit -m "feat: centered, padded writing canvas for editor and preview"
-```
-
-- [ ] **Step 8: Manual smoke (user-driven, real terminal)**
-
-```bash
-go run . README.md
-```
-Expected: text sits in a centered column with left/right margins and a top gap; a long paragraph soft-wraps at the column edge (word breaks, markup still visible); Up/Down move by visual line through a wrapped paragraph; `Ctrl+R` preview shares the same centered column; `Ctrl+T` still cycles themes; saving round-trips the file unchanged (no inserted line breaks).
-
----
-
-## Self-Review Notes
-
-**Spec coverage:**
-- A canvas (contentWidth clamp, left margin, top pad, status bar full-width, picker excluded) → Task 3.
-- B.1 word-aware wrapping with partition guarantee, span slicing → Task 1 (`wrapLine`, `sliceSpans`).
-- B.2 visual cursor mapping; Up/Down by visual row with goal column; Left/Right & Home/End logical; visual scroll → Task 2.
-- B.3 visual View with themed cursor cell → Task 2.
-- C preview shares the column → Task 3 (`setSize` sizes preview to contentWidth; `View` indents/pads it).
-- D structure/tests; `Bytes()` round-trip under wrap → Task 2 test.
-- Invariants: explicit foreground (sliceSpans preserves styles), markup-visible/display-only (buffer untouched; round-trip test), layout rendering-only (indent in app View) → Tasks 1–3.
-
-**Type consistency:** `segment`, `vrow`, `wrapLine`, `sliceSpans`, `buildVisual`, `cursorVIndex` defined in Task 1 are used unchanged in Task 2. `e.goalCol`, `e.setGoal`, `e.visualColOf`, `e.applyGoal` introduced in Task 2 are self-contained. App `contentWidth`/`leftMargin`/`topPad`/`indentLines` (Task 3) match their call sites in `setSize`/`View`.
-
-**Known follow-ups (not v1.2 blockers):** visual-row list rebuilt per render/move (no caching) — fine for note-sized files; visual Home/End deferred (logical); true thin-bar cursor not possible in-cell (themed cell instead); the `0.65` ratio and caps are constants, not config.
-```
docs/superpowers/specs/2026-06-27-glint-design.md +0 −170
@@ -1,170 +0,0 @@
-# glint — design spec
-
-**Date:** 2026-06-27
-**Status:** design approved, pre-implementation
-**Stack:** Go + Bubbletea (MVU) + Lipgloss + Glamour
-
-## What it is
-
-A pretty terminal markdown editor with glow-style rendering. Open a file, edit
-it with **live inline styling** (bold renders bold, headings colored/bold, links
-colored — while the raw markup characters stay visible), save it. Plus: jump to
-today's daily note, fuzzy-pick a file, and toggle a full glamour-rendered read
-view.
-
-Two faces, built in order:
-
-1. **Editor (v1, this spec).** A micro-like editor for editing/previewing any
- markdown doc from anywhere — `glint notes.md`, `glint ~/foo/README.md`,
- `glint --daily`. Vault-agnostic: works on a loose file or inside the vault.
- This is the core and the v1 deliverable.
-2. **Vault TUI (later version).** An Obsidian-vault companion layer on top of the
- editor — browse/navigate/search the vault, wikilink follow, tags, graph
- (not a replacement; Obsidian GUI stays primary). Out of scope for v1; the v1
- architecture is built so this bolts on without rework.
-
-Motivation: existing vault TUIs (ekphos, clin-rs, basalt, kimun) almost fit but
-hardcode the wrong things. ekphos was closest, but: (1) its editor leaves plain
-text at the terminal default foreground — unreadable in a light terminal;
-(2) daily-note path/format is hardcoded to `journal.<date>.md` in the vault root,
-incompatible with the user's `Daily/<date>.md` convention; (3) sort default is
-hardcoded and never persisted. glint fixes all three by design.
-
-## Non-goals (v1)
-
-Wikilink follow, in-content search, graph view, tag browsing, multi-pane layout,
-sort persistence, vim modality. Modeless editing only. Most of these belong to
-the **Vault TUI (later version)**, not the editor — see "What it is".
-
-## Editing model (decided)
-
-- **Modeless.** Standard typing + arrows. No vim modes in v1.
-- **Live inline styling, markup NOT concealed.** `**bold**` shows the asterisks,
- styled bold. `## Head` shows the `##`, styled. No cursor-reveal logic, no width
- changes from hidden characters — this is what keeps the editor tractable.
-- Terminals can't resize text, so "big heading" = bold + color (+ optional
- underline), not a larger font.
-
-## Architecture
-
-Bubbletea MVU. A top-level `model` holds a `mode` enum (Editor | Picker |
-Preview) and the sub-models. Exactly one view is active at a time. Each unit
-below has one purpose, a defined interface, and is testable in isolation.
-
-### 1. `editor` (core — the real work)
-
-Owns the buffer and all editing. **Knows nothing about files or the vault** —
-it is a pure text buffer + renderer. Save/load are wired by the top model.
-
-State: `lines []string` (per-line rune content; v1 plain slice is fine for
-vault-sized files), `cursor {row, col}`, `scroll` (viewport top), `dirty bool`.
-
-Responsibilities:
-- Input: insert/delete runes, newline/split, backspace/join, cursor movement
- (char/word/line/home/end/page), viewport scroll-follow.
-- Render: produce styled lines for the visible viewport via the styling layer.
-
-### 2. Styling layer (inside `editor`)
-
-For each **visible** line, a hand-rolled markdown scanner emits a list of spans
-`{text, style}`, where `style` is a Lipgloss style. The rendered line is the
-concatenation of styled spans, character-for-character aligned with the raw line
-(no insertions/deletions — markup stays visible).
-
-- **Block context** tracked across lines: fenced code blocks (```), YAML
- frontmatter (leading `---` … `---`), so inline rules are suppressed inside
- them.
-- Inline rules: headings (`#`..`######`), bold (`**`/`__`), italic (`*`/`_`),
- inline code (`` ` ``), links `[text](url)`, wikilinks `[[..]]` (styled only,
- not followed in v1), list markers (`-`/`*`/`+`/`N.`), blockquote (`>`).
-- **Every span — including plain prose — gets an explicit foreground from the
- theme. Never `Style{}` / terminal default.** This is the root-cause fix for the
- ekphos light-terminal bug.
-- Not a goldmark AST: an AST reflows and drops markup characters, which breaks
- char-exact alignment to the editable raw text. A line-oriented scanner with
- carried block state is the right tool here.
-
-### 3. `preview`
-
-Toggle key renders the current buffer text through **Glamour** (configured style)
-into a scrollable, read-only `viewport`. Here markup IS concealed — the full glow
-read experience. Esc returns to the editor at the same position.
-
-### 4. `picker`
-
-Vault file browser with fuzzy filter (Bubbles `list`). Walks `vault_dir` for
-`.md` files, ignoring dot-directories. Enter opens the selection in the editor.
-
-Daily-note action (own keybind): builds
-`<vault_dir>/<daily_subdir>/<format(today)>.md`; if missing, creates the
-directory and the file (optionally seeded from a template); opens it in the
-editor.
-
-### 5. `config` (TOML)
-
-The things ekphos hardcoded, made configurable:
-
-```toml
-vault_dir = "/Users/kortum/Humdrum"
-daily_subdir = "Daily"
-daily_format = "2006-01-02" # Go reference-time layout
-glamour_style = "dark" # builtin name or path to a style JSON
-```
-
-Loaded from `~/.config/glint/config.toml`. Sensible defaults if absent. A `theme`
-section (or reuse of `glamour_style`'s palette) supplies the explicit editor
-foreground/accent colors used by the styling layer.
-
-## Keybindings (v1, modeless)
-
-| Key | Action |
-|----------|--------------------------------|
-| `Ctrl+S` | Save current file |
-| `Ctrl+P` | Open file picker (fuzzy) |
-| `Ctrl+D` | Open/create today's daily note |
-| `Ctrl+R` | Toggle glamour read-preview |
-| `Esc` | Leave picker/preview → editor |
-| `Ctrl+Q` | Quit (prompt if dirty) |
-| arrows / typing | Normal text editing |
-
-(Exact chords finalizable during implementation; avoid clashes with terminal.)
-
-## Data flow
-
-1. Launch: parse flags (`glint [path]`, `glint --daily`), load config, build top
- model. With a path → load file into editor. With `--daily` → daily-note path.
- Bare → picker.
-2. Keystrokes → top model `Update` routes by `mode` to the active sub-model.
-3. Editor edits mutate buffer + set `dirty`. `Ctrl+S` writes `lines` to disk,
- clears `dirty`.
-4. `Ctrl+R` feeds buffer text to Glamour → preview viewport.
-5. Picker/daily selection → load file bytes → editor buffer → `mode = Editor`.
-
-## Error handling
-
-- File read/write errors surface in the status bar; never silent. A failed save
- keeps `dirty` true and shows the error.
-- Missing config → defaults. Malformed config → report the parse error and fall
- back to defaults rather than crashing.
-- Daily-note dir creation failure → status-bar error, stay in current view.
-
-## Testing
-
-- **Styling scanner:** pure unit tests — raw markdown line(s) + carried block
- state → expected spans. The highest-value tests; cover headings, bold/italic,
- code, links, wikilinks, lists, blockquotes, fence/frontmatter boundaries, and
- the plain-text-gets-explicit-fg invariant.
-- **Editor ops:** unit tests on the model — insert/delete/split/join/movement
- against expected buffer + cursor state.
-- **Update routing:** Bubbletea `Update` is testable by feeding messages and
- asserting resulting model state / mode transitions.
-- `preview` and `picker` are thin wrappers over Glamour / Bubbles `list`; smoke
- tests only.
-
-## Open items for implementation
-
-- Final keybinding chords (collision check vs terminal/Ghostty).
-- Whether the editor foreground/accent palette is its own `[theme]` table or
- derived from the chosen glamour style.
-- Daily-note template content (if any) — likely mirror the user's existing daily
- template minus script-generated callouts.
docs/superpowers/specs/2026-06-28-glint-theme-picker-design.md +0 −157
@@ -1,157 +0,0 @@
-# glint v1.1 — Theme System + Picker Overhaul (Design)
-
-**Status:** Approved design, pending implementation plan.
-
-**Motivation.** v1 shipped with a single hardcoded dark theme (`editor.DefaultDarkTheme`). On a light terminal the plain-text foreground (`#c0caf5`, near-white) is nearly invisible — confirmed by a screenshot of cream-background text. This adds light/dark themes, a third charm.land theme, OS auto-detection, a live toggle, and reworks the file picker to match the behavior of the user's existing `md` fzf navigator (modified-date sort, today's daily floated on top) plus a glamour preview pane and a new-note shortcut.
-
-This is a follow-on to the v1 design (`docs/superpowers/specs/2026-06-27-glint-design.md`) and editor plan (`docs/superpowers/plans/2026-06-27-glint-editor.md`); it preserves both v1 invariants.
-
-## Preserved invariants
-
-1. **Explicit foreground:** every emitted styled span — in every theme, light or dark — gets an explicit `Foreground`. No span ever falls back to the terminal default. (The light themes make this load-bearing for readability, not just correctness.)
-2. **Markup-visible:** the editor styling scanner still never adds or removes characters; the concatenation of a line's span texts equals the raw line. (Unchanged — this work does not touch the scanner's tokenizing logic, only the colors it pulls from.)
-
-## A. Theme system
-
-### A.1 New `internal/theme` package
-
-Theming moves out of `internal/editor` into a standalone `internal/theme` package so `editor`, `picker`, `app`, and `preview` can all consume themes without import cycles. (`editor.Theme`, `editor.DefaultDarkTheme`, and the editor's internal color references are replaced by `theme.Theme` and theme constructors. The scanner takes a `theme.Theme` argument exactly as it took `editor.Theme` before — a mechanical type move.)
-
-### A.2 `theme.Theme` struct
-
-Carries the eight markdown colors from v1 plus UI colors, all `lipgloss.Color`, all explicitly set:
-
-| Field | Use |
-|---|---|
-| `Text` | plain prose, default foreground |
-| `Heading` | headings (bold) |
-| `Code` | inline + fenced code |
-| `Link` | `[text](url)` |
-| `Wikilink` | `[[wikilink]]` |
-| `ListMarker` | list bullets / numbers |
-| `Blockquote` | blockquotes, frontmatter (muted) |
-| `Accent` | highlight — YAML frontmatter keys (section D) |
-| `Background` | app background |
-| `Muted` | secondary text (picker header, hints) |
-| `StatusFg` / `StatusBg` | status bar |
-| `SelFg` / `SelBg` | picker selected row |
-| `Pointer` | picker `▸` pointer, cursor accents |
-| `Name` (string) | theme id, e.g. `"flexoki-dark"` |
-| `GlamourStyle` (string) | glamour style this theme maps to (preview sync) |
-
-Every constructor sets every color field. A theme with any empty color field is a bug; a test asserts all fields non-empty for every registered theme.
-
-### A.3 Registered themes (concrete palettes)
-
-**Flexoki** (Steph Ango's palette — matches the user's `md` picker and vault ontology). Hexes lifted from the `md` `_md_palette` function and Flexoki's accent set.
-
-`FlexokiDark()` — `Name: "flexoki-dark"`, `GlamourStyle: "dark"`:
-- Background `#100F0F`, Text `#CECDC3`, Muted `#878580`, Blockquote `#878580`
-- Heading `#4385BE` (blue), Code `#879A39` (green), Link `#3AA99F` (cyan), Wikilink `#8B7EC8` (purple), ListMarker `#CE5D97` (magenta), Accent `#D0A215` (yellow)
-- StatusBg `#4385BE`, StatusFg `#100F0F`, SelBg `#D0A215`, SelFg `#100F0F`, Pointer `#CE5D97`
-
-`FlexokiLight()` — `Name: "flexoki-light"`, `GlamourStyle: "light"`:
-- Background `#FFFCF0`, Text `#100F0F`, Muted `#6F6E69`, Blockquote `#6F6E69`
-- Heading `#205EA6` (blue), Code `#66800B` (green), Link `#24837B` (cyan), Wikilink `#5E409D` (purple), ListMarker `#A02F6F` (magenta), Accent `#AD8301` (yellow)
-- StatusBg `#205EA6`, StatusFg `#FFFCF0`, SelBg `#AD8301`, SelFg `#FFFCF0`, Pointer `#A02F6F`
-
-**Charm** (charm.land / charmbracelet brand aesthetic). `Charm()` — `Name: "charm"`, `GlamourStyle: "dark"`:
-- Background `#16161E`, Text `#FFFDF5`, Muted `#6C6C8A`, Blockquote `#6C6C8A`
-- Heading `#FF5FAF` (charm hot pink), Code `#00FFA3` (mint), Link `#5DD5FF` (malibu cyan), Wikilink `#B575FF` (charple), ListMarker `#FF5FAF`, Accent `#FFD500` (citron)
-- StatusBg `#6B50FF` (charple), StatusFg `#FFFDF5`, SelBg `#FF5FAF`, SelFg `#16161E`, Pointer `#00FFA3`
-
-### A.4 Resolution and detection
-
-- `theme.ByName(name string) (Theme, bool)` — registry lookup over the three names above.
-- `theme.Detect() string` — returns `"flexoki-dark"` or `"flexoki-light"` from the OS. On macOS, runs `defaults read -g AppleInterfaceStyle`; output containing `Dark` → dark, anything else (including the non-zero exit when the key is unset, which means Light) → light. On non-macOS or on error → `"flexoki-dark"`.
-- `theme.Resolve(configValue string) Theme` — `"auto"` (or empty) → `ByName(Detect())`; a known name → that theme; an unknown name → `Detect()`'s theme (never errors, never returns an empty theme).
-
-### A.5 Config
-
-`config.Config` gains `Theme string` with toml key `theme`, default `"auto"`. The existing `GlamourStyle` key stays but changes role: it is now an **explicit override** of the theme's `GlamourStyle`. Preview style = `cfg.GlamourStyle` if the user set it non-empty in the file, else the active theme's `GlamourStyle`. (Default config leaves `glamour_style` effectively unset so the theme drives it; to preserve back-compat with v1's `glamour_style = "dark"` default, the default becomes empty string and the preview falls back to the theme.)
-
-### A.6 Live toggle
-
-`Ctrl+T` (currently unused; distinct from Tab) cycles the active theme in registry order `flexoki-light → flexoki-dark → charm → flexoki-light …` and re-renders. The app holds the active `theme.Theme`, passes it to the editor (which re-scans with the new colors), the status bar, and the picker. Toggling also updates the glamour style used by the next preview render.
-
-## B. Picker overhaul
-
-### B.1 Behavior (mirrors the `md` navigator)
-
-- **Default order (empty query): modified-date descending.** `walkMarkdown` returns each file with its mtime; the picker sorts newest-first.
-- **Today's daily note floated to the top** of the default order when the file exists (matches `md`'s `today_note` float). "Today's daily" = `cfg.DailyPath(time.Now())`.
-- **Query typed:** fuzzy rank as in v1 (`fuzzyMatch` subsequence + gap penalty), tie-broken by mtime descending.
-- Selection moves with Up/Down; `Enter` opens the highlighted file (existing dirty-guard from v1's confirm-then-discard still applies at the app layer).
-
-### B.2 Preview pane
-
-- Split layout via `lipgloss.JoinHorizontal`: match list on the left (~40% width), a rounded-bordered **glamour preview of the highlighted file** on the right (~60% width).
-- The preview reuses the `preview` package's glamour renderer, using the active theme's glamour style. It re-renders when the highlighted selection changes (read the file, render, load into a viewport). File-read or render errors show a short message in the preview pane, never crash.
-- The list column shows `▸` pointer on the selected row, `note ›` prompt above (the textinput), active-theme colors (SelFg/SelBg for the selected row, Muted for the header), rounded border around the whole picker.
-- Header hint line: ` ⌃N new · <vault-relative dir>` (keep it short; theme `Muted`).
-
-### B.3 New note (`Ctrl+N`)
-
-- `Ctrl+N` in the picker creates a note named after the current query (supports `Folder/Name`, appends `.md` if absent), under `cfg.VaultDir`, then opens it in the editor. Mirrors `md`'s Ctrl-N. Creates intermediate directories. If the file already exists, opens it rather than erroring. Empty query → no-op with a status message.
-- No template seeding in v1.1 (the `md` `_md_seed` behavior is out of scope); a new note opens empty.
-
-### B.4 Out of scope (v1.1)
-
-Full-text / ripgrep search mode (`md`'s ⌃F) is explicitly deferred. The picker remains title/path fuzzy only.
-
-## D. YAML frontmatter formatting
-
-v1 styles the entire leading YAML frontmatter block as flat muted text. v1.1 syntax-highlights it while preserving the markup-visible invariant (every character stays; concatenated spans equal the raw line). Highlighting reuses existing theme colors — **no new theme fields**:
-
-- The `---` open/close delimiters → `Muted`.
-- A `key:` line → the key (up to and including the colon) in `Accent`, a single space, then the value in `Text`. (Concrete use for the previously-reserved `Accent` field.)
-- A block/list value line (` - item`) → leading whitespace preserved, the `-` marker in `ListMarker`, the item text in `Text`.
-- A `#` comment line inside frontmatter → `Muted`.
-- A bare line with no `:` (e.g. a multi-line value continuation) → `Text`.
-
-Mechanics: this is handled inside the existing frontmatter branch of `scanLine` (the block-state path that already knows "we are between the leading `---` fences"). It splits each frontmatter line into spans at the first `": "` (or trailing `:`) boundary; the split is by rune index so every character is retained and the span texts concatenate back to the raw line exactly. Frontmatter is detected exactly as in v1 (`---` on row 0 until the next `---`); only its internal coloring changes. A test asserts, over a frontmatter corpus (keys, list values, comments, the delimiters), that `concat(spans).Text == rawLine` for every line and that keys/values/markers get the expected colors.
-
-This is independent of the editor body scanner (`scanInline`), which is unchanged.
-
-## C. Structure & testing
-
-New / changed files:
-
-```
-internal/theme/
- theme.go Theme struct, registry, ByName, Resolve, cycle order
- themes.go FlexokiLight, FlexokiDark, Charm constructors (concrete hexes)
- detect.go Detect() — macOS AppleInterfaceStyle, cross-platform fallback
- theme_test.go all-fields-set per theme; ByName; Resolve(auto/name/unknown); cycle order
- detect_test.go parse logic (inject the raw `defaults` output / a stubbed reader)
-internal/editor/
- scanner.go, editor.go take theme.Theme instead of editor.Theme (mechanical move; delete editor/theme.go)
- scanner.go frontmatter branch now syntax-highlights keys/values/markers/comments (section D)
- scanner_test.go frontmatter corpus: char-for-char preservation + per-element colors
-internal/picker/
- picker.go mtime walk, today-float, fuzzy+mtime sort, preview pane, Ctrl+N, theme colors
- picker_test.go walkMarkdown returns+sorts by mtime; today-float ordering; fuzzy+mtime tiebreak; new-note path building (pure)
-internal/preview/
- preview.go unchanged API; app passes the theme-derived glamour style
-internal/app/
- app.go hold active theme; Ctrl+T cycle; pass theme to editor/picker/status; Ctrl+N routing in picker; theme→glamour sync
- app_test.go Ctrl+T cycles theme + re-renders; Ctrl+N creates+opens; picker still opens/dismisses
-internal/config/
- config.go Theme field (toml `theme`, default "auto"); GlamourStyle default → "" (theme drives)
- config_test.go theme default + overlay
-main.go unchanged wiring (Start path already covers picker/daily/path)
-```
-
-- **Detection is tested without depending on the host OS**: `Detect()` delegates to an internal helper that parses a provided string (the raw `defaults` output) so the parse logic is unit-tested deterministically; the OS call is a thin wrapper around it.
-- **Theme correctness test**: every registered theme has all color fields non-empty (the explicit-foreground invariant, enforced for light too).
-- TDD throughout, executed with the same subagent-driven-development flow as v1 (fresh implementer + two-stage review per task, whole-branch review at the end).
-- `go vet ./...`, `go build ./...`, `go test ./...` clean; manual smoke in both a light and a dark terminal, plus `Ctrl+T` cycling and the picker preview.
-
-## Keybinds (additions)
-
-| Key | Action |
-|---|---|
-| `Ctrl+T` | cycle theme (flexoki-light → flexoki-dark → charm → …) |
-| `Ctrl+N` | (in picker) new note from query |
-
-All v1 keybinds unchanged: `Ctrl+S` save, `Ctrl+P` picker, `Ctrl+D` daily, `Ctrl+R` preview, `Esc` back, `Ctrl+Q` quit (confirm if dirty), and the v1.0 confirm-then-discard on `Ctrl+P`/`Ctrl+D` while dirty.
docs/superpowers/specs/2026-06-28-glint-writing-canvas-design.md +0 −77
@@ -1,77 +0,0 @@
-# glint v1.2 — Writing Canvas (Design)
-
-**Status:** Approved design, pending implementation plan.
-
-**Motivation.** v1 renders text flush against the left edge, full terminal width — it reads like a code editor, not a writing surface. The goal is an iA Writer–style canvas: a centered, comfortably-narrow text column with generous left/right margins and a little top air, text left-aligned inside that column, and long paragraphs that **soft-wrap** at the column edge. Aesthetic target: a mix of a terminal, charm.land, and iA Writer — mono text, near-black on off-white (the `flexoki-light` theme from v1.1), relaxed margins.
-
-This is the **second** v1.x increment. It builds on v1.1 (`docs/superpowers/specs/2026-06-28-glint-theme-picker-design.md`), specifically the themed editor (`editor` already consumes `theme.Theme`). **Sequencing: build v1.1 first, then this.** Both v1.1 and this increment modify `editor` rendering, so doing v1.1 first avoids churn.
-
-## Preserved invariants
-
-1. **Explicit foreground:** every styled span still gets an explicit foreground (unchanged — soft-wrap slices already-styled spans; it never produces an unstyled span).
-2. **Markup-visible:** the scanner still preserves characters exactly. Soft-wrapping is a **display-only** transformation: the logical buffer is untouched, `Bytes()` round-trips the exact logical lines, and the markup characters remain visible in every visual row.
-3. **Layout is rendering-only:** the centering margins and top padding are added to the rendered frame, never to the buffer. Saving a file never inserts margin spaces or wrap breaks.
-
-## A. The canvas (centering + padding)
-
-The app owns layout. Given terminal width `W` and height `H`:
-
-- **Column width (the measure):** `contentWidth = clamp(round(W × 0.65), 24, 100)`, further clamped to `≤ W` for tiny terminals. (Percentage-of-width, capped for readability and floored so it never collapses.)
-- **Left margin:** `(W − contentWidth) / 2`, applied equally on both sides by indenting every rendered content row.
-- **Top padding:** `1` blank row above the content for air.
-- **Status bar:** unchanged — full width, bottom row.
-- The editor and preview are sized to `contentWidth` and rendered into the centered column. The **picker keeps its own full-width split layout** (out of scope for centering).
-
-Row budget: `topPad (1) + textRows + statusBar (1) = H`, so `textRows = H − 2`.
-
-## B. Soft-wrapping editor
-
-The editor keeps its v1 model: logical `Lines []string` and a logical `Cursor{Row, Col}` in rune coordinates; all buffer ops (insert, newline, backspace, delete, left, right) are unchanged and operate on logical coordinates. What changes is **rendering and vertical navigation**, which become *visual-row* aware.
-
-### B.1 Wrapping
-
-- `wrapLine(line, width)` splits a logical line into **segments** (visual rows). It is **word-aware**: it breaks just after the last space that fits within `width`; a word longer than `width` is hard-broken at `width`. An empty line yields one empty segment.
-- **Partition guarantee:** segments partition the line's runes contiguously with no dropped or duplicated characters — `concat(segment texts) == line`. (The breaking space stays as the trailing rune of its segment.) This keeps cursor↔visual mapping exact.
-- A logical line's styled spans (from `ScanLines`) are sliced per segment by rune range, preserving styles (`sliceSpans`).
-
-### B.2 Visual cursor and navigation
-
-- The cursor's **visual position** is the segment of its logical line that contains `Cursor.Col` (the last segment when `Col` is at line end), and the visual column `Col − segment.start`.
-- **Up / Down move by visual row**, not logical row: they target the same **goal visual column** on the adjacent visual row and map it back to logical `{Row, Col}`. The goal column is remembered across consecutive Up/Down and reset whenever the cursor moves horizontally or the buffer changes (standard editor behavior).
-- **Left / Right stay logical** (rune-wise), naturally crossing wrap boundaries and logical line ends — unchanged from v1.
-- **Home / End stay logical** (start / end of the logical line) — unchanged from v1.
-- **Scroll is a visual-row index.** The viewport follows the cursor's visual row, keeping it within `[Scroll, Scroll+Height)`.
-
-### B.3 Rendering
-
-- `View` builds the visual-row list for the buffer, renders the window `[Scroll, Scroll+Height)`, draws the cursor on its visual row at its visual column (themed cursor cell — background `theme.Pointer`, foreground `theme.Background`; a TUI cannot draw iA's thin in-cell bar, so the cell is themed instead), and pads with blank rows to exactly `Height` rows. Output is `contentWidth`-wide (the app adds the left margin).
-
-## C. Preview canvas
-
-`Ctrl+R` glamour preview renders at `contentWidth` (glamour word-wraps to that width) and the app indents it by the same left margin and top padding, so the read view sits in the same column as the editor. The preview's existing viewport scrolling is unchanged.
-
-## D. Structure & testing
-
-```
-internal/editor/
- wrap.go NEW: segment, wrapLine, sliceSpans, visual-row builder, cursor index
- wrap_test.go NEW: word/hard wrap, partition guarantee, multibyte, empty line; sliceSpans boundaries
- editor.go MOD: Width = measure; visual View; visual MoveUp/MoveDown; goalCol; visual followCursor; themed cursor
- editor_test.go MOD: movement/view tests updated to visual semantics (expected churn)
-internal/app/
- app.go MOD: contentWidth/leftMargin/topPad; size editor+preview to measure; indent+center editor & preview; picker unchanged
- app_test.go MOD: a content-width/margin sanity test
-```
-
-- `wrapLine` and `sliceSpans` are pure and carry the high-value unit tests (partition guarantee, word vs hard break, multibyte runes, empty line, span slicing at and across boundaries).
-- Editor visual navigation is tested by constructing a buffer wider than the measure and asserting Down/Up land on the expected logical `{Row, Col}` for a known goal column, and that `Scroll` (visual) follows the cursor.
-- `Bytes()` round-trip test confirms wrapping never alters the buffer.
-- TDD throughout; `go vet ./...`, `go build ./...`, `go test ./...` clean; manual smoke in a real terminal: long paragraphs wrap inside a centered column with margins; Up/Down move visually; `Ctrl+R` preview shares the column.
-
-## E. Out of scope (v1.2)
-
-- Visual Home/End (stay logical).
-- Centering the picker (keeps its split).
-- A true thin-bar cursor (themed cell instead).
-- Configurable measure ratio / margins (the `0.65` ratio and caps are constants).
-- Reflow performance optimization (the visual-row list is rebuilt per render/move; fine for note-sized files, noted as a follow-up).
internal/app/app.go +4 −3
@@ -136,9 +136,10 @@ if msg.Type != tea.KeyCtrlQ {
a.quitArmed = false
}
// Disarm pending-discard unless the same action is being re-pressed.
- if !(msg.Type == tea.KeyCtrlF && a.pending == discardPicker) &&
- !(msg.Type == tea.KeyCtrlD && a.pending == discardDaily) &&
- !(msg.Type == tea.KeyCtrlN && a.pending == discardNew) {
+ repressed := (msg.Type == tea.KeyCtrlF && a.pending == discardPicker) ||
+ (msg.Type == tea.KeyCtrlD && a.pending == discardDaily) ||
+ (msg.Type == tea.KeyCtrlN && a.pending == discardNew)
+ if !repressed {
a.pending = discardNone
}
internal/config/config.go +10 −3
@@ -21,11 +21,18 @@ Theme string `toml:"theme"`
InboxDir string `toml:"inbox_dir"`
}
-// Default returns the built-in configuration used when no file is present.
+// Default returns the built-in configuration used when no file is present. The
+// vault defaults to $GLINT_VAULT, or the current working directory when that is
+// unset — a config-file vault_dir (applied in loadFromFile) overrides both.
func Default() Config {
- home, _ := os.UserHomeDir()
+ vault := os.Getenv("GLINT_VAULT")
+ if vault == "" {
+ if wd, err := os.Getwd(); err == nil {
+ vault = wd
+ }
+ }
return Config{
- VaultDir: filepath.Join(home, "Humdrum"),
+ VaultDir: vault,
DailySubdir: "Daily",
DailyFormat: "2006-01-02",
Theme: "auto",
internal/config/config_test.go +12 −0
@@ -132,3 +132,15 @@ if got := c.InboxRoot(); got != "/abs/inbox" {
t.Errorf("absolute InboxDir → %q, want /abs/inbox", got)
}
}
+
+func TestDefaultVaultUsesEnvThenCwd(t *testing.T) {
+ t.Setenv("GLINT_VAULT", "/explicit/vault")
+ if d := Default(); d.VaultDir != "/explicit/vault" {
+ t.Errorf("with GLINT_VAULT set: VaultDir = %q, want /explicit/vault", d.VaultDir)
+ }
+ t.Setenv("GLINT_VAULT", "")
+ wd, _ := os.Getwd()
+ if d := Default(); d.VaultDir != wd {
+ t.Errorf("without GLINT_VAULT: VaultDir = %q, want cwd %q", d.VaultDir, wd)
+ }
+}
internal/picker/wrap_overflow_test.go +3 −3
@@ -18,9 +18,9 @@ func TestListLabelsDoNotWrapOrOverflow(t *testing.T) {
root := t.TempDir()
names := []string{
"short.md",
- "ARCHER/Meetings/2026-06-18 ARCHER ABE Team Meeting Review.md",
- "Claude/Issues/humdrum/task-003 - Schedule-b2-backup.sh-and-b2-backup-ssd.sh-as-daily-launchd-jobs.md",
- "ARCHER/Working Files/Active-Member (we have a membership field).md",
+ "Meetings/2026-06-18 Weekly Project Sync Notes and Review.md",
+ "Issues/tracker/task-003 - schedule-nightly-backup-and-rotate-old-snapshots-cron-job.md",
+ "Working Files/Reference Material (longer parenthetical title here).md",
}
// Plus enough files to overfill the viewport — the real-world trigger is a
// vault of hundreds of notes, where a single wrapped label pushes the query
internal/preview/preview.go +1 −3
@@ -79,7 +79,6 @@ width = 80
}
opts := []glamour.TermRendererOption{glamour.WithWordWrap(width)}
- style := m.style
// If it exists as a file, use it as a path
if _, err := os.Stat(m.style); err == nil {
opts = append(opts, glamour.WithStylePath(m.style))
@@ -88,8 +87,7 @@ // If it's a known builtin name, use it
opts = append(opts, glamour.WithStandardStyle(m.style))
} else {
// Otherwise, fall back to "dark"
- style = "dark"
- opts = append(opts, glamour.WithStandardStyle(style))
+ opts = append(opts, glamour.WithStandardStyle("dark"))
}
return glamour.NewTermRenderer(opts...)
}
main.go +9 −0
@@ -12,7 +12,16 @@
tea "github.com/charmbracelet/bubbletea"
)
+// version is the build version, overridden at release time via
+// -ldflags "-X main.version=<v>" (the Homebrew formula sets it).
+var version = "dev"
+
func main() {
+ if a := os.Args[1:]; len(a) > 0 && (a[0] == "version" || a[0] == "--version" || a[0] == "-v") {
+ fmt.Println("glint", version)
+ return
+ }
+
cfg, err := config.Load()
if err != nil {
fmt.Fprintln(os.Stderr, "glint: config:", err)