├── .cargo └── config.toml ├── .envrc ├── .github ├── FUNDING.yml └── workflows │ ├── flakehub.yml │ ├── nix-build.yml │ ├── publish.yml │ └── release-please.yml ├── .gitignore ├── .release-please-config.json ├── .release-please-manifest.json ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── flake.lock ├── flake.nix ├── lemmy-help-LICENSE ├── luaCATS.md ├── result ├── src ├── cli.rs ├── lexer.rs ├── lexer │ └── token.rs ├── lib.rs ├── main.rs ├── parser.rs ├── parser │ ├── node.rs │ └── tags │ │ ├── alias.rs │ │ ├── brief.rs │ │ ├── class.rs │ │ ├── divider.rs │ │ ├── enum.rs │ │ ├── func.rs │ │ ├── mod.rs │ │ ├── module.rs │ │ ├── see.rs │ │ ├── tag.rs │ │ ├── type.rs │ │ └── usage.rs ├── vimcat.rs └── vimdoc.rs ├── stylua.toml └── tests ├── basic.rs ├── golden.rs ├── golden ├── alias_and_type.lua ├── alias_and_type.txt ├── brief.lua ├── brief.txt ├── classes.lua ├── classes.txt ├── divider_and_tag.lua ├── divider_and_tag.txt ├── enum.lua ├── enum.txt ├── export.lua ├── export.txt ├── functions.lua ├── functions.txt ├── module.lua ├── module.txt ├── multi_extension.lua ├── multi_extension.txt ├── multiline_param.lua ├── multiline_param.txt ├── namespaced_classes.lua ├── namespaced_classes.txt ├── private.lua ├── private.txt ├── toc.lua ├── toc.txt ├── usage.lua └── usage.txt ├── types.rs └── with_settings.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [alias] 2 | rr = "run --offline --features=cli" 3 | bb = "build --offline --features=cli --release" 4 | ii = "install --offline --features=cli --path ." 5 | tt = "nextest run --all-features" 6 | 7 | [target.x86_64-pc-windows-msvc] 8 | rustflags = ["-C", "target-feature=+crt-static"] 9 | 10 | [target.i686-pc-windows-msvc] 11 | rustflags = ["-C", "target-feature=+crt-static"] 12 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use flake . -Lv 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [mrcjkb] 4 | -------------------------------------------------------------------------------- /.github/workflows/flakehub.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Publish tags to FlakeHub" 3 | on: 4 | push: 5 | tags: 6 | - "v?[0-9]+.[0-9]+.[0-9]+*" 7 | workflow_dispatch: 8 | inputs: 9 | tag: 10 | description: "The existing tag to publish to FlakeHub" 11 | type: "string" 12 | required: true 13 | jobs: 14 | flakehub-publish: 15 | runs-on: "ubuntu-20.04" 16 | permissions: 17 | id-token: "write" 18 | contents: "read" 19 | steps: 20 | - uses: "actions/checkout@v4" 21 | with: 22 | ref: "${{ (inputs.tag != null) && format('refs/tags/{0}', inputs.tag) || '' }}" 23 | - uses: "DeterminateSystems/nix-installer-action@main" 24 | - uses: "DeterminateSystems/flakehub-push@main" 25 | with: 26 | visibility: "public" 27 | name: "mrcjkb/vimcats" 28 | tag: "${{ inputs.tag }}" 29 | 30 | -------------------------------------------------------------------------------- /.github/workflows/nix-build.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Nix build" 3 | on: 4 | pull_request: 5 | push: 6 | branches: [ main ] 7 | jobs: 8 | build: 9 | name: Nix build (${{ matrix.job.target }}) 10 | runs-on: ${{ matrix.job.os }} 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | job: 15 | - { os: ubuntu-24.04, target: x86_64-linux } 16 | - { os: macos-13, target: x86_64-darwin } 17 | - { os: macos-14, target: aarch64-darwin } 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: DeterminateSystems/nix-installer-action@v9 21 | - uses: cachix/cachix-action@v14 22 | with: 23 | name: mrcjkb 24 | authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}' 25 | - name: Checks 26 | run: nix flake check -Lv --accept-flake-config 27 | shell: bash 28 | - name: Build package 29 | run: nix build ".#packages.${{matrix.job.target}}.default" --accept-flake-config 30 | shell: bash 31 | - name: Build devShell 32 | run: nix build ".#devShells.${{matrix.job.target}}.default" --accept-flake-config 33 | shell: bash 34 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Cargo publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | release: 8 | types: 9 | - created 10 | workflow_dispatch: 11 | 12 | jobs: 13 | cargo-publish: 14 | runs-on: ubuntu-22.04 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: dtolnay/rust-toolchain@stable 18 | 19 | - name: cargo-release Cache 20 | id: cargo_release_cache 21 | uses: actions/cache@v3 22 | with: 23 | path: ~/.cargo/bin/cargo-release 24 | key: ${{ runner.os }}-cargo-release 25 | 26 | - run: cargo install cargo-release 27 | if: steps.cargo_release_cache.outputs.cache-hit != 'true' 28 | 29 | - name: cargo login 30 | run: cargo login ${{ secrets.CRATES_IO_API_TOKEN }} 31 | 32 | - name: "cargo release publish" 33 | run: |- 34 | cargo release \ 35 | publish \ 36 | --workspace \ 37 | --all-features \ 38 | --allow-branch HEAD \ 39 | --no-confirm \ 40 | --no-verify \ 41 | --execute 42 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Release Please 3 | 4 | on: 5 | push: 6 | branches: 7 | - main 8 | 9 | permissions: 10 | contents: write 11 | pull-requests: write 12 | 13 | jobs: 14 | release-please: 15 | name: release-please 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: googleapis/release-please-action@v4 19 | with: 20 | release-type: rust 21 | include-component-in-tag: false 22 | token: ${{ secrets.PAT }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /result-* 3 | .pre-commit-config.yaml 4 | .direnv/ 5 | -------------------------------------------------------------------------------- /.release-please-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "bootstrap-sha": "a47ff44d8a2ebef201fa9fd749bc08b9e9035147", 3 | "packages": { 4 | ".": { 5 | "release-type": "rust" 6 | }, 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.release-please-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | ".": "1.1.1" 3 | } 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [1.1.1](https://github.com/mrcjkb/vimcats/compare/v1.1.0...v1.1.1) (2025-05-15) 4 | 5 | 6 | ### Bug Fixes 7 | 8 | * func tag spillover if line == TW ([#23](https://github.com/mrcjkb/vimcats/issues/23)) ([044a6c9](https://github.com/mrcjkb/vimcats/commit/044a6c987d9f19a719a17565a3498a0a88bc5078)) 9 | 10 | ## [1.1.0](https://github.com/mrcjkb/vimcats/compare/v1.0.2...v1.1.0) (2024-09-04) 11 | 12 | 13 | ### Features 14 | 15 | * **parser:** support `---[@enum](https://github.com/enum)` ([#18](https://github.com/mrcjkb/vimcats/issues/18)) ([060b1c4](https://github.com/mrcjkb/vimcats/commit/060b1c44a9c47b72963bd4bcd736a38bcc2fb120)) 16 | 17 | ## [1.0.2](https://github.com/mrcjkb/vimcats/compare/v1.0.1...v1.0.2) (2024-08-26) 18 | 19 | 20 | ### Bug Fixes 21 | 22 | * list index fields ([#14](https://github.com/mrcjkb/vimcats/issues/14)) ([79aeb65](https://github.com/mrcjkb/vimcats/commit/79aeb657dfde512d5027db57c4e5793cf83f20d9)) 23 | * multiple class extensions ([#12](https://github.com/mrcjkb/vimcats/issues/12)) ([ebe2691](https://github.com/mrcjkb/vimcats/commit/ebe269100cc9dc277ae37a66e6b49f25aac6e01c)) 24 | 25 | ## [1.0.1](https://github.com/mrcjkb/vimcats/compare/v1.0.0...v1.0.1) (2024-08-26) 26 | 27 | 28 | ### Bug Fixes 29 | 30 | * extending classes with dot separator ([#10](https://github.com/mrcjkb/vimcats/issues/10)) ([8fc9829](https://github.com/mrcjkb/vimcats/commit/8fc9829d81ec1de5dc920329a2e355e2bd9d51ad)) 31 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "ahash" 7 | version = "0.8.11" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" 10 | dependencies = [ 11 | "cfg-if", 12 | "once_cell", 13 | "version_check", 14 | "zerocopy", 15 | ] 16 | 17 | [[package]] 18 | name = "allocator-api2" 19 | version = "0.2.18" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" 22 | 23 | [[package]] 24 | name = "bitflags" 25 | version = "2.6.0" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" 28 | 29 | [[package]] 30 | name = "bstr" 31 | version = "1.10.0" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "40723b8fb387abc38f4f4a37c09073622e41dd12327033091ef8950659e6dc0c" 34 | dependencies = [ 35 | "memchr", 36 | "regex-automata", 37 | "serde", 38 | ] 39 | 40 | [[package]] 41 | name = "cfg-if" 42 | version = "1.0.0" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 45 | 46 | [[package]] 47 | name = "chumsky" 48 | version = "0.9.3" 49 | source = "registry+https://github.com/rust-lang/crates.io-index" 50 | checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9" 51 | dependencies = [ 52 | "hashbrown", 53 | ] 54 | 55 | [[package]] 56 | name = "comfy-table" 57 | version = "7.1.1" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "b34115915337defe99b2aff5c2ce6771e5fbc4079f4b506301f5cf394c8452f7" 60 | dependencies = [ 61 | "strum", 62 | "strum_macros", 63 | "unicode-width", 64 | ] 65 | 66 | [[package]] 67 | name = "console" 68 | version = "0.15.8" 69 | source = "registry+https://github.com/rust-lang/crates.io-index" 70 | checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" 71 | dependencies = [ 72 | "encode_unicode", 73 | "lazy_static", 74 | "libc", 75 | "windows-sys 0.52.0", 76 | ] 77 | 78 | [[package]] 79 | name = "either" 80 | version = "1.13.0" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" 83 | 84 | [[package]] 85 | name = "encode_unicode" 86 | version = "0.3.6" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" 89 | 90 | [[package]] 91 | name = "errno" 92 | version = "0.3.9" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" 95 | dependencies = [ 96 | "libc", 97 | "windows-sys 0.52.0", 98 | ] 99 | 100 | [[package]] 101 | name = "fastrand" 102 | version = "2.1.0" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" 105 | 106 | [[package]] 107 | name = "goldenfile" 108 | version = "1.7.1" 109 | source = "registry+https://github.com/rust-lang/crates.io-index" 110 | checksum = "a0d5c44265baec620ea19c97b4ce9f068e28f8c3d7faccc483f02968b5e3c587" 111 | dependencies = [ 112 | "scopeguard", 113 | "similar-asserts", 114 | "tempfile", 115 | "yansi", 116 | ] 117 | 118 | [[package]] 119 | name = "hashbrown" 120 | version = "0.14.5" 121 | source = "registry+https://github.com/rust-lang/crates.io-index" 122 | checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" 123 | dependencies = [ 124 | "ahash", 125 | "allocator-api2", 126 | ] 127 | 128 | [[package]] 129 | name = "heck" 130 | version = "0.5.0" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" 133 | 134 | [[package]] 135 | name = "itertools" 136 | version = "0.13.0" 137 | source = "registry+https://github.com/rust-lang/crates.io-index" 138 | checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" 139 | dependencies = [ 140 | "either", 141 | ] 142 | 143 | [[package]] 144 | name = "lazy_static" 145 | version = "1.5.0" 146 | source = "registry+https://github.com/rust-lang/crates.io-index" 147 | checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" 148 | 149 | [[package]] 150 | name = "lexopt" 151 | version = "0.3.0" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "baff4b617f7df3d896f97fe922b64817f6cd9a756bb81d40f8883f2f66dcb401" 154 | 155 | [[package]] 156 | name = "libc" 157 | version = "0.2.158" 158 | source = "registry+https://github.com/rust-lang/crates.io-index" 159 | checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" 160 | 161 | [[package]] 162 | name = "linux-raw-sys" 163 | version = "0.4.14" 164 | source = "registry+https://github.com/rust-lang/crates.io-index" 165 | checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" 166 | 167 | [[package]] 168 | name = "memchr" 169 | version = "2.7.4" 170 | source = "registry+https://github.com/rust-lang/crates.io-index" 171 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 172 | 173 | [[package]] 174 | name = "once_cell" 175 | version = "1.19.0" 176 | source = "registry+https://github.com/rust-lang/crates.io-index" 177 | checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" 178 | 179 | [[package]] 180 | name = "proc-macro2" 181 | version = "1.0.86" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" 184 | dependencies = [ 185 | "unicode-ident", 186 | ] 187 | 188 | [[package]] 189 | name = "quote" 190 | version = "1.0.36" 191 | source = "registry+https://github.com/rust-lang/crates.io-index" 192 | checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" 193 | dependencies = [ 194 | "proc-macro2", 195 | ] 196 | 197 | [[package]] 198 | name = "regex-automata" 199 | version = "0.4.7" 200 | source = "registry+https://github.com/rust-lang/crates.io-index" 201 | checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" 202 | 203 | [[package]] 204 | name = "rustix" 205 | version = "0.38.34" 206 | source = "registry+https://github.com/rust-lang/crates.io-index" 207 | checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" 208 | dependencies = [ 209 | "bitflags", 210 | "errno", 211 | "libc", 212 | "linux-raw-sys", 213 | "windows-sys 0.52.0", 214 | ] 215 | 216 | [[package]] 217 | name = "rustversion" 218 | version = "1.0.9" 219 | source = "registry+https://github.com/rust-lang/crates.io-index" 220 | checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" 221 | 222 | [[package]] 223 | name = "scopeguard" 224 | version = "1.2.0" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 227 | 228 | [[package]] 229 | name = "serde" 230 | version = "1.0.208" 231 | source = "registry+https://github.com/rust-lang/crates.io-index" 232 | checksum = "cff085d2cb684faa248efb494c39b68e522822ac0de72ccf08109abde717cfb2" 233 | dependencies = [ 234 | "serde_derive", 235 | ] 236 | 237 | [[package]] 238 | name = "serde_derive" 239 | version = "1.0.208" 240 | source = "registry+https://github.com/rust-lang/crates.io-index" 241 | checksum = "24008e81ff7613ed8e5ba0cfaf24e2c2f1e5b8a0495711e44fcd4882fca62bcf" 242 | dependencies = [ 243 | "proc-macro2", 244 | "quote", 245 | "syn", 246 | ] 247 | 248 | [[package]] 249 | name = "similar" 250 | version = "2.6.0" 251 | source = "registry+https://github.com/rust-lang/crates.io-index" 252 | checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" 253 | dependencies = [ 254 | "bstr", 255 | "unicode-segmentation", 256 | ] 257 | 258 | [[package]] 259 | name = "similar-asserts" 260 | version = "1.5.0" 261 | source = "registry+https://github.com/rust-lang/crates.io-index" 262 | checksum = "e041bb827d1bfca18f213411d51b665309f1afb37a04a5d1464530e13779fc0f" 263 | dependencies = [ 264 | "console", 265 | "similar", 266 | ] 267 | 268 | [[package]] 269 | name = "strum" 270 | version = "0.26.3" 271 | source = "registry+https://github.com/rust-lang/crates.io-index" 272 | checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" 273 | 274 | [[package]] 275 | name = "strum_macros" 276 | version = "0.26.4" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" 279 | dependencies = [ 280 | "heck", 281 | "proc-macro2", 282 | "quote", 283 | "rustversion", 284 | "syn", 285 | ] 286 | 287 | [[package]] 288 | name = "syn" 289 | version = "2.0.75" 290 | source = "registry+https://github.com/rust-lang/crates.io-index" 291 | checksum = "f6af063034fc1935ede7be0122941bafa9bacb949334d090b77ca98b5817c7d9" 292 | dependencies = [ 293 | "proc-macro2", 294 | "quote", 295 | "unicode-ident", 296 | ] 297 | 298 | [[package]] 299 | name = "tempfile" 300 | version = "3.12.0" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" 303 | dependencies = [ 304 | "cfg-if", 305 | "fastrand", 306 | "once_cell", 307 | "rustix", 308 | "windows-sys 0.59.0", 309 | ] 310 | 311 | [[package]] 312 | name = "textwrap" 313 | version = "0.16.0" 314 | source = "registry+https://github.com/rust-lang/crates.io-index" 315 | checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" 316 | 317 | [[package]] 318 | name = "unicode-ident" 319 | version = "1.0.5" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" 322 | 323 | [[package]] 324 | name = "unicode-segmentation" 325 | version = "1.11.0" 326 | source = "registry+https://github.com/rust-lang/crates.io-index" 327 | checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" 328 | 329 | [[package]] 330 | name = "unicode-width" 331 | version = "0.1.10" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" 334 | 335 | [[package]] 336 | name = "version_check" 337 | version = "0.9.5" 338 | source = "registry+https://github.com/rust-lang/crates.io-index" 339 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" 340 | 341 | [[package]] 342 | name = "vimcats" 343 | version = "1.1.1" 344 | dependencies = [ 345 | "chumsky", 346 | "comfy-table", 347 | "goldenfile", 348 | "itertools", 349 | "lexopt", 350 | "textwrap", 351 | ] 352 | 353 | [[package]] 354 | name = "windows-sys" 355 | version = "0.52.0" 356 | source = "registry+https://github.com/rust-lang/crates.io-index" 357 | checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" 358 | dependencies = [ 359 | "windows-targets", 360 | ] 361 | 362 | [[package]] 363 | name = "windows-sys" 364 | version = "0.59.0" 365 | source = "registry+https://github.com/rust-lang/crates.io-index" 366 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 367 | dependencies = [ 368 | "windows-targets", 369 | ] 370 | 371 | [[package]] 372 | name = "windows-targets" 373 | version = "0.52.6" 374 | source = "registry+https://github.com/rust-lang/crates.io-index" 375 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 376 | dependencies = [ 377 | "windows_aarch64_gnullvm", 378 | "windows_aarch64_msvc", 379 | "windows_i686_gnu", 380 | "windows_i686_gnullvm", 381 | "windows_i686_msvc", 382 | "windows_x86_64_gnu", 383 | "windows_x86_64_gnullvm", 384 | "windows_x86_64_msvc", 385 | ] 386 | 387 | [[package]] 388 | name = "windows_aarch64_gnullvm" 389 | version = "0.52.6" 390 | source = "registry+https://github.com/rust-lang/crates.io-index" 391 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 392 | 393 | [[package]] 394 | name = "windows_aarch64_msvc" 395 | version = "0.52.6" 396 | source = "registry+https://github.com/rust-lang/crates.io-index" 397 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 398 | 399 | [[package]] 400 | name = "windows_i686_gnu" 401 | version = "0.52.6" 402 | source = "registry+https://github.com/rust-lang/crates.io-index" 403 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 404 | 405 | [[package]] 406 | name = "windows_i686_gnullvm" 407 | version = "0.52.6" 408 | source = "registry+https://github.com/rust-lang/crates.io-index" 409 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 410 | 411 | [[package]] 412 | name = "windows_i686_msvc" 413 | version = "0.52.6" 414 | source = "registry+https://github.com/rust-lang/crates.io-index" 415 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 416 | 417 | [[package]] 418 | name = "windows_x86_64_gnu" 419 | version = "0.52.6" 420 | source = "registry+https://github.com/rust-lang/crates.io-index" 421 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 422 | 423 | [[package]] 424 | name = "windows_x86_64_gnullvm" 425 | version = "0.52.6" 426 | source = "registry+https://github.com/rust-lang/crates.io-index" 427 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 428 | 429 | [[package]] 430 | name = "windows_x86_64_msvc" 431 | version = "0.52.6" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 434 | 435 | [[package]] 436 | name = "yansi" 437 | version = "1.0.1" 438 | source = "registry+https://github.com/rust-lang/crates.io-index" 439 | checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" 440 | 441 | [[package]] 442 | name = "zerocopy" 443 | version = "0.7.35" 444 | source = "registry+https://github.com/rust-lang/crates.io-index" 445 | checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" 446 | dependencies = [ 447 | "zerocopy-derive", 448 | ] 449 | 450 | [[package]] 451 | name = "zerocopy-derive" 452 | version = "0.7.35" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" 455 | dependencies = [ 456 | "proc-macro2", 457 | "quote", 458 | "syn", 459 | ] 460 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vimcats" 3 | version = "1.1.1" 4 | description = "LuaCATS parser and vimdoc transformer" 5 | authors = ["mrcjkb "] 6 | edition = "2021" 7 | homepage = "https://github.com/mrcjkb/vimcats" 8 | repository = "https://github.com/mrcjkb/vimcats" 9 | license = "GPL-2.0+" 10 | readme = "README.md" 11 | keywords = ["parser", "lua", "LuaCATS", "vimdoc", "neovim"] 12 | categories = ["parsing", "command-line-utilities"] 13 | exclude = [ 14 | ".aur/**", 15 | ".cargo/**", 16 | ".github/**", 17 | "tests/**", 18 | ".gitignore", 19 | ] 20 | 21 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 22 | 23 | [[bin]] 24 | name = "vimcats" 25 | required-features = ["cli"] 26 | 27 | [dependencies] 28 | chumsky = { version = "0.9.3", default-features = false } 29 | textwrap = { version = "0.16.0", default-features = false, optional = true } 30 | comfy-table = { version = "7.1.1", default-features = false, optional = true } 31 | lexopt = { version = "0.3.0", default-features = false, optional = true } 32 | itertools = "0.13.0" 33 | 34 | [dev-dependencies] 35 | goldenfile = "1.7.1" 36 | 37 | [features] 38 | vimdoc = ["dep:textwrap", "dep:comfy-table"] 39 | cli = ["vimdoc", "dep:lexopt"] 40 | 41 | [profile.release] 42 | lto = true 43 | strip = true 44 | codegen-units = 1 45 | opt-level = 3 46 | panic = 'abort' 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2 (or later), June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | 342 | GPL LICENSE EXCEPTION FOR DERIVED OPEN SOURCE SOFTWARE 343 | 344 | The GPL version 2 license applies only to the Nix CI infrastructure provided 345 | by this template repository, including any modifications made to the infrastructure. 346 | Any software that uses or is derived from this template may be licensed under any 347 | OSI approved open source license, without being subject to the GPL version 2 license 348 | of the infrastructure. 349 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

:cat2: vimCATS :book:

2 |

A CLI to generate vimdoc from LuaCATS. Forked from lemmy-help.

3 | 4 | 5 | ![vimcats](https://user-images.githubusercontent.com/24727447/164423469-b26fea39-2ef7-497c-8156-5a4c01bc30f8.gif "Generating help docs") 6 | 7 | ### What? 8 | 9 | `vimcats` is a LuaCATS parser as well as a CLI 10 | which takes that parsed tree and converts it into vim help docs. 11 | 12 | ### Installation 13 | 14 | [![Packaging status](https://repology.org/badge/vertical-allrepos/vimcats.svg)](https://repology.org/project/vimcats/versions) 15 | 16 | - Using `cargo` 17 | 18 | ```bash 19 | cargo install vimcats --features=cli 20 | ``` 21 | 22 | ### LuaCATS 23 | 24 | To properly generate docs you should follow the luaCATS spec. 25 | The parser is capable of parsing most (not all) of the LuaCATS syntax. 26 | You can read the following doc which can give you an idea on how to 27 | properly write LuaCATS annotations. 28 | 29 | - [Writing LuaCATS annotations](./luaCATS.md) 30 | 31 | ### Usage 32 | 33 | Using the CLI is simple just give it the path to the lua files; 34 | it will parse them and prints help doc to `stdout`. 35 | 36 | ```bash 37 | vimcats /path/to/{first,second,third}.lua > doc/PLUGIN_NAME.txt 38 | ``` 39 | 40 | ### CLI 41 | 42 | ```text 43 | vimcats 44 | 45 | USAGE: 46 | vimcats [FLAGS] [OPTIONS] ... 47 | 48 | ARGS: 49 | ... Path to lua files 50 | 51 | FLAGS: 52 | -h, --help Print help information 53 | -v, --version Print version information 54 | -M, --no-modeline Don't print modeline at the end 55 | -f, --prefix-func Prefix function name with ---@mod name 56 | -a, --prefix-alias Prefix ---@alias tag with return/---@mod name 57 | -c, --prefix-class Prefix ---@class tag with return/---@mod name 58 | -t, --prefix-type Prefix ---@type tag with ---@mod name 59 | --expand-opt Expand '?' (optional) to 'nil' type 60 | 61 | OPTIONS: 62 | -i, --indent Controls the indent width [default: 4] 63 | -l, --layout Vimdoc text layout [default: 'default'] 64 | - "default" : Default layout 65 | - "compact[:n=0]" : Aligns [desc] with 66 | and uses {n}, if provided, to indent the 67 | following new lines. This option only 68 | affects ---@field and ---@param tags 69 | - "mini[:n=0]" : Aligns [desc] from the start 70 | and uses {n}, if provided, to indent the 71 | following new lines. This option affects 72 | ---@field, ---@param and ---@return tags 73 | 74 | USAGE: 75 | vimcats /path/to/first.lua /path/to/second.lua > doc/PLUGIN_NAME.txt 76 | vimcats -c -a /path/to/{first,second,third}.lua > doc/PLUGIN_NAME.txt 77 | vimcats --layout compact:2 /path/to/plugin.lua > doc/PLUGIN_NAME.txt 78 | 79 | NOTES: 80 | - The order of parsing + rendering is relative to the given files 81 | ``` 82 | 83 | ### CI 84 | 85 | ```yaml 86 | name: vimcats 87 | 88 | on: [push] 89 | 90 | env: 91 | PLUGIN_NAME: plugin-name 92 | 93 | jobs: 94 | docs: 95 | runs-on: ubuntu-latest 96 | name: luaCATS to vimdoc 97 | steps: 98 | - uses: actions/checkout@v4 99 | 100 | - name: Install Rust 101 | uses: dtolnay/rust-toolchain@master 102 | 103 | - name: Install vimcats 104 | run: cargo install vimcats --features=cli 105 | 106 | - name: Generate docs 107 | run: vimcats [args] > doc/${{env.PLUGIN_NAME}}.txt 108 | 109 | - name: Commit 110 | uses: stefanzweifel/git-auto-commit-action@v4 111 | with: 112 | branch: ${{ github.head_ref }} 113 | commit_message: "chore(docs): auto-generate vimdoc" 114 | file_pattern: doc/*.txt 115 | ``` 116 | 117 | ### Nix flake 118 | 119 | This project provides a flake so you can use it with frameworks 120 | like [git-hooks.nix](https://github.com/cachix/git-hooks.nix). 121 | 122 | Here is basic example: 123 | 124 | > [!NOTE] 125 | > 126 | > You will likely want to ajust the flake to be used 127 | > with multiple systems. 128 | 129 | ```nix 130 | { 131 | inputs = { 132 | git-hooks.url = "github:cachix/git-hooks.nix"; 133 | vimcats.url = "github:mrcjkb/vimcats"; 134 | }; 135 | 136 | outputs = { 137 | self, 138 | nixpkgs, 139 | git-hooks, 140 | vimcats, 141 | ... 142 | }: let 143 | system = "x86_64-linux"; 144 | pkgs = nixpkgs.legacyPackages.${system}; 145 | docgen = final.writeShellApplication { 146 | name = "docgen"; 147 | runtimeInputs = [ 148 | inputs.vimcats.packages.${final.system}.default 149 | ]; 150 | text = '' 151 | mkdir -p doc 152 | vimcats [args] > doc/.txt 153 | ''; 154 | }; 155 | git-hooks-check = git-hooks.lib.${system}.run { 156 | src = self; 157 | hooks = { 158 | docgen = { 159 | enable = true; 160 | name = "docgen"; 161 | entry = "${pkgs.docgen}/bin/docgen"; 162 | files = "\\.(lua)$"; 163 | pass_filenames = false; 164 | }; 165 | }; 166 | }; 167 | in { 168 | devShells.${system}.default = { 169 | pkgs.mkShell { 170 | buildInputs = [ 171 | docgen 172 | ]; 173 | shellHook = '' 174 | # Installs a docgen pre-commit hook 175 | ${git-hooks-check.shellHook} 176 | ''; 177 | }; 178 | }; 179 | checks.${system} = { 180 | inherit git-hooks-check; 181 | }; 182 | }; 183 | } 184 | ``` 185 | 186 | ### Credits 187 | 188 | - [lemmy-help](https://github.com/numToStr/lemmy-help) 189 | - TJ's [docgen](https://github.com/tjdevries/tree-sitter-lua#docgen) module 190 | - [mini.doc](https://github.com/echasnovski/mini.nvim#minidoc) from `mini.nvim` plugin 191 | 192 | 193 | ### License 194 | 195 | This project is [licensed](./LICENSE) according to GPL version 2 196 | or (at your option) any later version. 197 | 198 | lemmy-help (from which this project is forked) 199 | is [licensed](./lemmy-help-LICENSE) according to MIT. 200 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-compat": { 4 | "flake": false, 5 | "locked": { 6 | "lastModified": 1696426674, 7 | "narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=", 8 | "owner": "edolstra", 9 | "repo": "flake-compat", 10 | "rev": "0f9255e01c2351cc7d116c072cb317785dd33b33", 11 | "type": "github" 12 | }, 13 | "original": { 14 | "owner": "edolstra", 15 | "repo": "flake-compat", 16 | "type": "github" 17 | } 18 | }, 19 | "flake-parts": { 20 | "inputs": { 21 | "nixpkgs-lib": "nixpkgs-lib" 22 | }, 23 | "locked": { 24 | "lastModified": 1725234343, 25 | "narHash": "sha256-+ebgonl3NbiKD2UD0x4BszCZQ6sTfL4xioaM49o5B3Y=", 26 | "owner": "hercules-ci", 27 | "repo": "flake-parts", 28 | "rev": "567b938d64d4b4112ee253b9274472dc3a346eb6", 29 | "type": "github" 30 | }, 31 | "original": { 32 | "owner": "hercules-ci", 33 | "repo": "flake-parts", 34 | "type": "github" 35 | } 36 | }, 37 | "git-hooks": { 38 | "inputs": { 39 | "flake-compat": "flake-compat", 40 | "gitignore": "gitignore", 41 | "nixpkgs": [ 42 | "nixpkgs" 43 | ], 44 | "nixpkgs-stable": "nixpkgs-stable" 45 | }, 46 | "locked": { 47 | "lastModified": 1725438226, 48 | "narHash": "sha256-lL4hQ+g2qiZ02WfidLkrujaT23c6E2Wm7S0ZQhSB8Jk=", 49 | "owner": "mrcjkb", 50 | "repo": "git-hooks.nix", 51 | "rev": "ec0f4d97f48a1f32bd87804e2390f03999790ec0", 52 | "type": "github" 53 | }, 54 | "original": { 55 | "owner": "mrcjkb", 56 | "ref": "clippy", 57 | "repo": "git-hooks.nix", 58 | "type": "github" 59 | } 60 | }, 61 | "gitignore": { 62 | "inputs": { 63 | "nixpkgs": [ 64 | "git-hooks", 65 | "nixpkgs" 66 | ] 67 | }, 68 | "locked": { 69 | "lastModified": 1709087332, 70 | "narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=", 71 | "owner": "hercules-ci", 72 | "repo": "gitignore.nix", 73 | "rev": "637db329424fd7e46cf4185293b9cc8c88c95394", 74 | "type": "github" 75 | }, 76 | "original": { 77 | "owner": "hercules-ci", 78 | "repo": "gitignore.nix", 79 | "type": "github" 80 | } 81 | }, 82 | "nixpkgs": { 83 | "locked": { 84 | "lastModified": 1725910328, 85 | "narHash": "sha256-n9pCtzGZ0httmTwMuEbi5E78UQ4ZbQMr1pzi5N0LAG8=", 86 | "owner": "NixOS", 87 | "repo": "nixpkgs", 88 | "rev": "5775c2583f1801df7b790bf7f7d710a19bac66f4", 89 | "type": "github" 90 | }, 91 | "original": { 92 | "owner": "NixOS", 93 | "ref": "nixpkgs-unstable", 94 | "repo": "nixpkgs", 95 | "type": "github" 96 | } 97 | }, 98 | "nixpkgs-lib": { 99 | "locked": { 100 | "lastModified": 1725233747, 101 | "narHash": "sha256-Ss8QWLXdr2JCBPcYChJhz4xJm+h/xjl4G0c0XlP6a74=", 102 | "type": "tarball", 103 | "url": "https://github.com/NixOS/nixpkgs/archive/356624c12086a18f2ea2825fed34523d60ccc4e3.tar.gz" 104 | }, 105 | "original": { 106 | "type": "tarball", 107 | "url": "https://github.com/NixOS/nixpkgs/archive/356624c12086a18f2ea2825fed34523d60ccc4e3.tar.gz" 108 | } 109 | }, 110 | "nixpkgs-stable": { 111 | "locked": { 112 | "lastModified": 1720386169, 113 | "narHash": "sha256-NGKVY4PjzwAa4upkGtAMz1npHGoRzWotlSnVlqI40mo=", 114 | "owner": "NixOS", 115 | "repo": "nixpkgs", 116 | "rev": "194846768975b7ad2c4988bdb82572c00222c0d7", 117 | "type": "github" 118 | }, 119 | "original": { 120 | "owner": "NixOS", 121 | "ref": "nixos-24.05", 122 | "repo": "nixpkgs", 123 | "type": "github" 124 | } 125 | }, 126 | "root": { 127 | "inputs": { 128 | "flake-parts": "flake-parts", 129 | "git-hooks": "git-hooks", 130 | "nixpkgs": "nixpkgs" 131 | } 132 | } 133 | }, 134 | "root": "root", 135 | "version": 7 136 | } 137 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "A CLI to generate vim/nvim help doc from emmylua"; 3 | 4 | nixConfig = { 5 | extra-substituters = "https://mrcjkb.cachix.org"; 6 | extra-trusted-public-keys = "mrcjkb.cachix.org-1:KhpstvH5GfsuEFOSyGjSTjng8oDecEds7rbrI96tjA4="; 7 | }; 8 | 9 | inputs = { 10 | nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 11 | flake-parts.url = "github:hercules-ci/flake-parts"; 12 | git-hooks = { 13 | # TODO: https://github.com/cachix/git-hooks.nix/pull/396 14 | # url = "github:cachix/git-hooks.nix"; 15 | url = "github:mrcjkb/git-hooks.nix?ref=clippy"; 16 | inputs.nixpkgs.follows = "nixpkgs"; 17 | }; 18 | }; 19 | 20 | outputs = inputs @ { 21 | self, 22 | nixpkgs, 23 | flake-parts, 24 | git-hooks, 25 | ... 26 | }: 27 | flake-parts.lib.mkFlake {inherit inputs;} { 28 | systems = [ 29 | "x86_64-linux" 30 | "x86_64-darwin" 31 | "aarch64-linux" 32 | "aarch64-darwin" 33 | ]; 34 | perSystem = {system, ...}: let 35 | pkgs = import nixpkgs { 36 | inherit system; 37 | overlays = [ 38 | self.overlays.default 39 | ]; 40 | }; 41 | git-hooks-check = git-hooks.lib.${system}.run { 42 | src = self; 43 | hooks = { 44 | alejandra.enable = true; 45 | rustfmt.enable = true; 46 | clippy = { 47 | enable = true; 48 | settings = { 49 | denyWarnings = true; 50 | allFeatures = true; 51 | }; 52 | extraPackages = with pkgs.vimcats; buildInputs ++ nativeBuildInputs; 53 | }; 54 | cargo-check.enable = true; 55 | }; 56 | settings = { 57 | rust.check.cargoDeps = pkgs.rustPlatform.importCargoLock { 58 | lockFile = ./Cargo.lock; 59 | }; 60 | }; 61 | }; 62 | in { 63 | devShells.default = pkgs.mkShell { 64 | name = "vimcats devShell"; 65 | buildInputs = 66 | pkgs.vimcats.buildInputs 67 | ++ pkgs.vimcats.nativeBuildInputs 68 | ++ self.checks.${system}.git-hooks-check.enabledPackages 69 | ++ (with pkgs; [ 70 | rust-analyzer 71 | cargo-nextest 72 | ]); 73 | inherit (git-hooks-check) shellHook; 74 | doCheck = false; 75 | }; 76 | 77 | packages = rec { 78 | default = vimcats; 79 | inherit (pkgs) vimcats; 80 | }; 81 | 82 | checks = rec { 83 | default = git-hooks-check; 84 | inherit git-hooks-check; 85 | }; 86 | }; 87 | flake = { 88 | overlays.default = final: prev: { 89 | vimcats = final.rustPlatform.buildRustPackage { 90 | pname = "vimcats"; 91 | 92 | src = self; 93 | 94 | version = ((final.lib.importTOML "${self}/Cargo.toml").package).version; 95 | 96 | cargoLock = { 97 | lockFile = ./Cargo.lock; 98 | }; 99 | 100 | buildFeatures = ["cli"]; 101 | 102 | meta = with final.lib; { 103 | description = "CLI for generating vimdoc from LuaCATS annotations"; 104 | license = with licenses; [mit]; 105 | mainProgram = "vimcats"; 106 | }; 107 | }; 108 | }; 109 | }; 110 | }; 111 | } 112 | -------------------------------------------------------------------------------- /lemmy-help-LICENSE: -------------------------------------------------------------------------------- 1 | MIT License Copyright (c) 2022 Vikas Rajbanshi 2 | 3 | Permission is hereby granted, free of 4 | charge, to any person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, copy, modify, merge, 7 | publish, distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to the 9 | following conditions: 10 | 11 | The above copyright notice and this permission notice 12 | (including the next paragraph) shall be included in all copies or substantial 13 | portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 18 | EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 19 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /luaCATS.md: -------------------------------------------------------------------------------- 1 | ## Writing LuaCATS 2 | 3 | > [!NOTE] 4 | > 5 | > `vimcats` aims to be compatible with [LLS LuaCATS annotations](https://luals.github.io/wiki/annotations/) 6 | > with some small add-ons to better support the vimdoc generation. 7 | 8 | Following are the tags that you can use to create docs 9 | 10 | ### Brief 11 | 12 | This tag can be used to describe a module or even to add some footnote etc. 13 | 14 | - Syntax 15 | 16 | ```lua 17 | ---@brief [[ 18 | ---@comment 19 | ---@brief ]] 20 | ``` 21 | 22 | - Input 23 | 24 | ```lua 25 | ---@brief [[ 26 | ---Any summary you wanted to write you can write here. 27 | ---There is no formatting here, 28 | ---the way you write in here, will be shown 29 | ---exactly in the help-doc 30 | --- 31 | ---An empty line can be used to denote a paragraph 32 | --- 33 | ---You can also write anything, like ordered list 34 | --- 1. first 35 | --- 2. second 36 | --- 3. third 37 | --- 38 | ---Some code blocks, but IDK whether it will be highlighted or not 39 | --- 40 | ---> 41 | --- for i = 1, 10, 1 do 42 | --- print(("%s Lua is awesome"):format(i)) 43 | --- end 44 | ---< 45 | --- 46 | ---NOTE: remember there is no formatting or text wrapping 47 | ---@brief ]] 48 | ``` 49 | 50 | - Output 51 | 52 | ```help 53 | Any summary you wanted to write you can write here. 54 | There is no formatting here, 55 | the way you write in here, will be shown 56 | exactly in the help-doc 57 | 58 | An empty line can be used to denote a paragraph 59 | 60 | You can also write anything, like ordered list 61 | 1. first 62 | 2. second 63 | 3. third 64 | 65 | Some code blocks, but IDK whether it will be highlighted or not 66 | 67 | > 68 | for i = 1, 10, 1 do 69 | print(("%s Lua is awesome"):format(i)) 70 | end 71 | < 72 | 73 | NOTE: remember there is no formatting or text wrapping 74 | ``` 75 | 76 | ### Module 77 | 78 | This tag can be used to add a heading for a section. This tag also has the following properties: 79 | 80 | 1. This can appear multiple times in a file but only the last `---@mod` will be used to rename prefixes. 81 | 82 | > Use `--prefix-{func,alias,class,type}` cli options to rename function, alias, class, and type name prefixes relatively 83 | > See [`tests/renaming`](./tests/renaming.rs) 84 | 85 | 2. Also adds a entries in the [`Table of Contents`](#table-of-contents) 86 | 87 | - Syntax 88 | 89 | ```lua 90 | ---@mod [desc] 91 | ``` 92 | 93 | - Input 94 | 95 | ```lua 96 | ---@mod mod.intro Introduction 97 | ---@brief [[ 98 | --- 99 | ---We can have multiple `---@mod` tags so that we can have a block only for text. 100 | ---This is for the cases where you want bunch of block only just for text 101 | ---and does not contains any code. 102 | --- 103 | ---You can write anything in here like some usage or something: 104 | --- 105 | ---> 106 | ---require('Comment').setup({ 107 | --- ignore = '^$', 108 | --- pre_hook = function(ctx) 109 | --- require('Comment.jsx').calculate(ctx) 110 | --- end 111 | ---}) 112 | ---< 113 | --- 114 | ---@brief ]] 115 | 116 | ---@mod mod.Human Human module 117 | 118 | local H = {} 119 | 120 | ---@class Human The Homosapien 121 | ---@field legs number Total number of legs 122 | ---@field hands number Total number of hands 123 | ---@field brain boolean Does humans have brain? 124 | 125 | ---Default traits of a human 126 | ---@type Human 127 | H.DEFAULT = { 128 | legs = 2, 129 | hands = 2, 130 | brain = false, 131 | } 132 | 133 | ---Creates a Human 134 | ---@return Human 135 | ---@usage `require('Human'):create()` 136 | function H:create() 137 | return setmetatable(self.DEFAULT, { __index = self }) 138 | end 139 | 140 | return H 141 | ``` 142 | 143 | - Output 144 | 145 | ```help 146 | ================================================================================ 147 | Introduction *mod.intro* 148 | 149 | 150 | We can have multiple `---@mod` tags so that we can have a block only for text. 151 | This is for the cases where you want bunch of block only just for text 152 | and does not contains any code. 153 | 154 | You can write anything in here like some usage or something: 155 | 156 | > 157 | require('Comment').setup({ 158 | ignore = '^$', 159 | pre_hook = function(ctx) 160 | require('Comment.jsx').calculate(ctx) 161 | end 162 | }) 163 | < 164 | 165 | 166 | ================================================================================ 167 | Human module *mod.Human* 168 | 169 | Human *Human* 170 | The Homosapien 171 | 172 | Fields: ~ 173 | {legs} (number) Total number of legs 174 | {hands} (number) Total number of hands 175 | {brain} (boolean) Does humans have brain? 176 | 177 | 178 | U.DEFAULT *U.DEFAULT* 179 | Default traits of a human 180 | 181 | Type: ~ 182 | (Human) 183 | 184 | 185 | U:create() *U:create* 186 | Creates a Human 187 | 188 | Returns: ~ 189 | {Human} 190 | 191 | Usage: ~ 192 | >lua 193 | require('Human'):create() 194 | < 195 | ``` 196 | 197 | ### Table of Contents 198 | 199 | This tag can be used to generate a _Table of Contents_ section. It uses [`---@mod`](#module) tags for the entries. 200 | 201 | - Syntax 202 | 203 | ```lua 204 | ---@toc 205 | ``` 206 | 207 | - Input 208 | 209 | ```lua 210 | ---@toc my-plugin.contents 211 | 212 | ---@mod first.module First Module 213 | 214 | ---@mod second.module Second Module 215 | 216 | ---@mod third.module Third Module 217 | 218 | local U = {} 219 | 220 | return U 221 | ``` 222 | 223 | - Output 224 | 225 | ```help 226 | ================================================================================ 227 | Table of Contents *my-plugin.contents* 228 | 229 | First Module······················································|first.module| 230 | Second Module····················································|second.module| 231 | Third Module······················································|third.module| 232 | 233 | ================================================================================ 234 | First Module *first.module* 235 | 236 | ================================================================================ 237 | Second Module *second.module* 238 | 239 | ================================================================================ 240 | Third Module *third.module* 241 | ``` 242 | 243 | ### Tag 244 | 245 | This tag can used to create an alternate tag for your module, functions etc. 246 | 247 | - Syntax 248 | 249 | ```lua 250 | ---@tag 251 | ``` 252 | 253 | - Input 254 | 255 | ```lua 256 | ---@tag cool-tag 257 | ---@tag another-cool-tag 258 | ``` 259 | 260 | - Output 261 | 262 | ``` 263 | *cool-tag* 264 | *another-cool-tag* 265 | ``` 266 | 267 | ### Divider 268 | 269 | This tag can be used to add a divider/separator between section or anything you desire 270 | 271 | - Syntax 272 | 273 | ```lua 274 | ---@divider 275 | ``` 276 | 277 | - Input 278 | 279 | ```lua 280 | ---@divider - 281 | ---@divider = 282 | ---@divider ~ 283 | ``` 284 | 285 | - Output 286 | 287 | ```help 288 | -------------------------------------------------------------------------------- 289 | 290 | ================================================================================ 291 | 292 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 293 | ``` 294 | 295 | ### Functions 296 | 297 | A function contains multiple tags which form its structure. Like `---@param` for parameter, `---@return` for the return value, `---@see` for other related things and [`---@usage`](#usage) for example 298 | 299 | - Syntax 300 | 301 | ```lua 302 | ---@comment 303 | ---@param [description] 304 | ---@comment 305 | ---@return [ [comment] | [name] #] 306 | ---@comment 307 | ---@see 308 | ---@usage `` 309 | ``` 310 | 311 | > NOTE: All tag can be used multiple times except `---@usage` 312 | 313 | - Input 314 | 315 | ```lua 316 | local U = {} 317 | 318 | ---NOTE: Local functions are not part of the documentation 319 | ---Multiply two integer and print it 320 | ---@param this number First number 321 | ---@param that number Second number 322 | local function mul(this, that) 323 | print(this * that) 324 | end 325 | 326 | ---Add two integer and print it 327 | ---@param this number First number 328 | ---@param that number Second number 329 | ---@usage `require("module.U").sum(10, 5)` 330 | function U.sum(this, that) 331 | print(this + that) 332 | end 333 | 334 | ---Subtract second from the first integer 335 | ---@param this number First number 336 | ---@param that number Second number 337 | ---@return number 338 | ---@usage [[ 339 | ---local M = require("module.U") 340 | --- 341 | ---print(M.sub(10 - 5)) 342 | ---@usage ]] 343 | function U.sub(this, that) 344 | return this - that 345 | end 346 | 347 | ---This is a magical function 348 | ---@param this number Non-magical number #1 349 | ---@param that number Non-magical number #2 350 | ---@return number _ The magical number #1 351 | ---@return number _ The magical number #2 352 | ---@see U.mul 353 | ---@see U.sum 354 | ---@see U.sub 355 | U.magical = function(this, that) 356 | return (U.mul(this, that) / U.sum(that, this)), (U.sum(this, that) * U.sub(that, this)) 357 | end 358 | 359 | ---Trigger a rebuild of one or more projects. 360 | ---@param opts table|nil optional configuration options: 361 | --- * {select_mode} (JdtProjectSelectMode) Show prompt 362 | --- to select projects or select all. Defaults 363 | --- to 'prompt' 364 | --- 365 | --- * {full_build} (boolean) full rebuild or 366 | --- incremental build. Defaults to true (full build) 367 | ---@param reserverd table|nil reserved for the future use 368 | ---@return boolean _ This is description of return 369 | ---statement that can be expanded to mutliple lines 370 | function U.multi_line(opts, reserverd) 371 | print(vim.inspect(opts), vim.inspect(reserverd)) 372 | return true 373 | end 374 | 375 | return U 376 | ``` 377 | 378 | - Output 379 | 380 | ```help 381 | U.sum({this}, {that}) *U.sum* 382 | Add two integer and print it 383 | 384 | Parameters: ~ 385 | {this} (number) First number 386 | {that} (number) Second number 387 | 388 | Usage: ~ 389 | >lua 390 | require("module.U").sum(10, 5) 391 | < 392 | 393 | U.sub({this}, {that}) *U.sub* 394 | Subtract second from the first integer 395 | 396 | Parameters: ~ 397 | {this} (number) First number 398 | {that} (number) Second number 399 | 400 | Returns: ~ 401 | {number} 402 | 403 | Usage: ~ 404 | >lua 405 | local M = require("module.U") 406 | 407 | print(M.sub(10 - 5)) 408 | < 409 | 410 | 411 | U.magical({this}, {that}) *U.magical* 412 | This is a magical function 413 | 414 | Parameters: ~ 415 | {this} (number) Non-magical number #1 416 | {that} (number) Non-magical number #2 417 | 418 | Returns: ~ 419 | {number} The magical number #1 420 | {number} The magical number #2 421 | 422 | See: ~ 423 | |U.mul| 424 | |U.sum| 425 | |U.sub| 426 | 427 | 428 | U.multi_line({opts}, {reserverd}) *U.multi_line* 429 | Trigger a rebuild of one or more projects. 430 | 431 | Parameters: ~ 432 | {opts} (table|nil) optional configuration options: 433 | * {select_mode} (JdtProjectSelectMode) Show prompt 434 | to select projects or select all. Defaults 435 | to 'prompt' 436 | 437 | * {full_build} (boolean) full rebuild or 438 | incremental build. Defaults to true (full build) 439 | {reserverd} (table|nil) reserved for the future use 440 | 441 | Returns: ~ 442 | {boolean} This is description of return 443 | statement that can be expanded to mutliple lines 444 | ``` 445 | 446 | ### Class 447 | 448 | Classes can be used to better structure your code and can be referenced as an argument to a function or it's return value. You can define it once and use it multiple times. 449 | 450 | - Syntax 451 | 452 | ```lua 453 | ---@comment 454 | ---@class [(exact)] [: ] 455 | ---@comment 456 | ---@field [public|protected|private] [desc] 457 | ---@see 458 | ``` 459 | 460 | > NOTE: `---@field` and `---@see` can be used multiple times 461 | 462 | - Input 463 | 464 | ```lua 465 | local H = {} 466 | 467 | ---The Homosapien 468 | ---@class Human 469 | ---@field legs number Total number of legs 470 | ---@field hands number Total number of hands 471 | ---@field brain boolean Does humans have brain? 472 | ---Traits that one human can have 473 | ---It could be one, two or hundered 474 | ---@field trait table 475 | ---@field protected heart boolean Heart is protected 476 | ---@field private IQ number We need to hide this 477 | 478 | ---@class XMen : Human 479 | ---@field power number Power quantifier 480 | 481 | ---Creates a Human 482 | ---@return Human 483 | ---@usage `require('Human'):create()` 484 | function H:create() 485 | return setmetatable({ 486 | legs = 2, 487 | hands = 2, 488 | brain = false 489 | }, { __index = self }) 490 | end 491 | 492 | return H 493 | ``` 494 | 495 | - Output 496 | 497 | ```help 498 | Human *Human* 499 | The Homosapien 500 | 501 | Fields: ~ 502 | {legs} (number) Total number of legs 503 | {hands} (number) Total number of hands 504 | {brain} (boolean) Does humans have brain? 505 | {trait} (table) Traits that one human can have 506 | It could be one, two or hundered 507 | 508 | 509 | XMen : Homosapien *XMen* 510 | 511 | Fields: ~ 512 | {power} (number) Power quantifier 513 | 514 | 515 | H:create() *H:create* 516 | Creates a Human 517 | 518 | Returns: ~ 519 | {Human} 520 | 521 | Usage: ~ 522 | >lua 523 | require('Human'):create() 524 | < 525 | ``` 526 | 527 | ### Type 528 | 529 | You can use `---@type` to document static objects, constants etc. 530 | 531 | - Syntax 532 | 533 | ```lua 534 | ---@comment 535 | ---@type [desc] 536 | ---@see 537 | ---@usage `` 538 | ``` 539 | 540 | - Input 541 | 542 | ```lua 543 | local U = {} 544 | 545 | ---@class Chai Ingredients for making chai 546 | ---@field milk string 1.5 cup 547 | ---@field water string 0.5 cup 548 | ---@field sugar string 3 tablespoon 549 | ---@field tea_leaves string 2 tablespoon 550 | ---@field cardamom string 2 pieces 551 | 552 | ---A object containing the recipe for making chai 553 | ---@type Chai 554 | U.chai = { 555 | milk = "1.5 Cup", 556 | water = "0.5 Cup", 557 | sugar = "3 table spoon", 558 | tea_leaves = "2 table spoon", 559 | cardamom = "2 pieces", 560 | } 561 | 562 | return U 563 | ``` 564 | 565 | - Output 566 | 567 | ```help 568 | Chai *Chai* 569 | Ingredients for making chai 570 | 571 | Fields: ~ 572 | {milk} (string) 1.5 cup 573 | {water} (string) 0.5 cup 574 | {sugar} (string) 3 tablespoon 575 | {tea_leaves} (string) 2 tablespoon 576 | {cardamom} (string) 2 pieces 577 | 578 | 579 | U.chai *U.chai* 580 | A object containing the recipe for making chai 581 | 582 | Type: ~ 583 | (Chai) 584 | ``` 585 | 586 | ### Usage 587 | 588 | This tag is used to show code usage of functions and [`---@type`](#type). Code inside `---@usage` will be rendered as codeblock. Optionally, a `lang` can be provided to get syntax highlighting (defaults to `lua`). 589 | 590 | - Syntax 591 | 592 | 1. Single-line 593 | 594 | ```lua 595 | ---@usage [lang] `` 596 | ``` 597 | 598 | 2. Multi-line 599 | 600 | ```lua 601 | ---@usage [lang] [[ 602 | ---... 603 | ---@usage ]] 604 | ``` 605 | 606 | - Input 607 | 608 | ```lua 609 | local U = {} 610 | 611 | ---Prints a message 612 | ---@param msg string Message 613 | ---@usage lua [[ 614 | ---require("module.U").sum(10, 5) 615 | ---@usage ]] 616 | function U.echo(msg) 617 | print(msg) 618 | end 619 | 620 | ---Add two integer and print it 621 | ---@param this number First number 622 | ---@param that number Second number 623 | ---@usage `require("module.U").sum(10, 5)` 624 | function U.sum(this, that) 625 | print(this + that) 626 | end 627 | 628 | return U 629 | ``` 630 | 631 | - Output 632 | 633 | ``` 634 | U.echo({msg}) *U.echo* 635 | Prints a message 636 | 637 | Parameters: ~ 638 | {msg} (string) Message 639 | 640 | Usage: ~ 641 | >lua 642 | require("module.U").sum(10, 5) 643 | < 644 | 645 | 646 | U.sum({this}, {that}) *U.sum* 647 | Add two integer and print it 648 | 649 | Parameters: ~ 650 | {this} (number) First number 651 | {that} (number) Second number 652 | 653 | Usage: ~ 654 | >lua 655 | require("module.U").sum(10, 5) 656 | < 657 | ``` 658 | 659 | ### Alias 660 | 661 | This tag can be used to make a type alias. It is helpful if you are using the same the type multiple times. 662 | 663 | - Syntax 664 | 665 | ```lua 666 | ---@comment 667 | ---@alias 668 | ``` 669 | 670 | - Input 671 | 672 | ```lua 673 | local U = {} 674 | 675 | ---All the lines in the buffer 676 | ---@alias Lines string[] 677 | 678 | ---Returns all the content of the buffer 679 | ---@return Lines 680 | function U.get_all() 681 | return vim.api.nvim_buf_get_lines(0, 0, -1, false) 682 | end 683 | 684 | return U 685 | ``` 686 | 687 | - Output 688 | 689 | ```help 690 | Lines *Lines* 691 | All the lines in the buffer 692 | 693 | Type: ~ 694 | string[] 695 | 696 | 697 | U.get_all() *U.get_all* 698 | Returns all the content of the buffer 699 | 700 | Returns: ~ 701 | {Lines} 702 | ``` 703 | 704 | ### Enum 705 | 706 | You can define a (pseudo) enum using [`---@alias`](#alias). 707 | 708 | - Syntax 709 | 710 | ```lua 711 | ---@alias 712 | ---| '' [# description] 713 | ---| `` [# description] 714 | ``` 715 | 716 | - Input 717 | 718 | ```lua 719 | local U = {} 720 | 721 | ---Vim operator-mode motions. 722 | --- 723 | ---Read `:h map-operator` 724 | ---@alias VMode 725 | ---| '"line"' # Vertical motion 726 | ---| '"char"' # Horizontal motion 727 | ---| 'v' 728 | ---| `some.ident` # Some identifier 729 | 730 | ---Global vim mode 731 | ---@type VMode 732 | U.VMODE = 'line' 733 | 734 | return U 735 | ``` 736 | 737 | - Output 738 | 739 | ```help 740 | VMode *VMode* 741 | Vim operator-mode motions. 742 | 743 | Read `:h map-operator` 744 | 745 | Variants: ~ 746 | ("line") Vertical motion 747 | ("char") Horizontal motion 748 | ("v") 749 | (some.ident) Some identifier 750 | 751 | 752 | U.VMODE *U.VMODE* 753 | Global vim mode 754 | 755 | Type: ~ 756 | (VMode) 757 | ``` 758 | 759 | ### Private 760 | 761 | One of the following tags can be used to discard any part of the code that is not considered a part of the public API. All these tags behaves exactly same when it comes to vimdoc generation but have different use cases when used together with LLS. 762 | 763 | - Spec: [`---@private`](https://github.com/sumneko/lua-language-server/wiki/Annotations#private), [`---@protected`](https://github.com/sumneko/lua-language-server/wiki/Annotations#protected), [`---@package`](https://github.com/sumneko/lua-language-server/wiki/Annotations#package) 764 | 765 | - Syntax 766 | 767 | ```lua 768 | ---@private 769 | 770 | ---@protected 771 | 772 | ---@package 773 | ``` 774 | 775 | - Input 776 | 777 | ```lua 778 | local U = {} 779 | 780 | ---@private 781 | ---This is a private function which is exported 782 | ---But not considered as part of the API 783 | function U.private() 784 | print('I am private!') 785 | end 786 | 787 | ---Only this will be documented 788 | function U.ok() 789 | print('Ok! I am exported') 790 | end 791 | 792 | ---@protected 793 | function U.no_luacats() 794 | print('Protected func with no LuaCATS!') 795 | end 796 | 797 | return U 798 | ``` 799 | 800 | - Output 801 | 802 | ```help 803 | U.ok() *U.ok* 804 | Only this will be documented 805 | ``` 806 | 807 | ### Export 808 | 809 | This tag is used to manually tag the exported object. This is required for cases where `vimcats` is unable to parse the `return` statement at the end such as `return setmetatable(...)`. But keep in mind the following: 810 | 811 | 1. Anything after this tag is NA, so make sure this is the last tag 812 | 2. Tag should be followed by the exact identifier that needs to be exported 813 | 3. This has nothing to do with `---@mod` 814 | 815 | - Syntax 816 | 817 | ```lua 818 | ---@export 819 | ``` 820 | 821 | - Input 822 | 823 | ```lua 824 | ---@mod module.config Configuration 825 | 826 | local Config = {} 827 | 828 | ---Get the config 829 | ---@return number 830 | function Config:get() 831 | return 3.14 832 | end 833 | 834 | ---@export Config 835 | return setmetatable(Config, { 836 | __index = function(this, k) 837 | return this.state[k] 838 | end, 839 | __newindex = function(this, k, v) 840 | this.state[k] = v 841 | end, 842 | }) 843 | ``` 844 | 845 | - Output 846 | 847 | ```help 848 | ================================================================================ 849 | Configuration *module.config* 850 | 851 | Config:get() *Config:get* 852 | Get the config 853 | 854 | Returns: ~ 855 | {number} 856 | ``` 857 | -------------------------------------------------------------------------------- /result: -------------------------------------------------------------------------------- 1 | /nix/store/hc02f8zp87akhzkx8iwi8b9np2cdd7pv-vimcats-1.1.0 -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use vimcats::{vimdoc::VimDoc, FromLuaCATS, Layout, Settings, VimCats}; 2 | 3 | use lexopt::{ 4 | Arg::{Long, Short, Value}, 5 | Parser, ValueExt, 6 | }; 7 | use std::{ffi::OsString, fs::read_to_string, path::PathBuf, str::FromStr}; 8 | 9 | pub const NAME: &str = env!("CARGO_PKG_NAME"); 10 | pub const VERSION: &str = env!("CARGO_PKG_VERSION"); 11 | pub const DESC: &str = env!("CARGO_PKG_DESCRIPTION"); 12 | pub const AUTHOR: &str = env!("CARGO_PKG_AUTHORS"); 13 | 14 | pub struct Cli { 15 | modeline: bool, 16 | settings: Settings, 17 | files: Vec, 18 | } 19 | 20 | impl Default for Cli { 21 | fn default() -> Self { 22 | Self { 23 | modeline: true, 24 | settings: Settings::default(), 25 | files: vec![], 26 | } 27 | } 28 | } 29 | 30 | impl Cli { 31 | pub fn new() -> Result { 32 | let mut c = Cli::default(); 33 | let mut parser = Parser::from_env(); 34 | 35 | while let Some(arg) = parser.next()? { 36 | match arg { 37 | Short('v') | Long("version") => { 38 | println!("{NAME} {VERSION}"); 39 | std::process::exit(0); 40 | } 41 | Short('h') | Long("help") => { 42 | Self::help(); 43 | std::process::exit(0); 44 | } 45 | Short('l') | Long("layout") => { 46 | let layout = parser.value()?; 47 | let Some(l) = layout.to_str() else { 48 | return Err(lexopt::Error::MissingValue { 49 | option: Some("layout".into()), 50 | }); 51 | }; 52 | c.settings.layout = 53 | Layout::from_str(l).map_err(|_| lexopt::Error::UnexpectedValue { 54 | option: "layout".into(), 55 | value: l.into(), 56 | })?; 57 | } 58 | Short('i') | Long("indent") => { 59 | c.settings.indent_width = parser.value()?.parse()?; 60 | } 61 | Short('M') | Long("no-modeline") => c.modeline = false, 62 | Short('f') | Long("prefix-func") => c.settings.prefix_func = true, 63 | Short('a') | Long("prefix-alias") => c.settings.prefix_alias = true, 64 | Short('c') | Long("prefix-class") => c.settings.prefix_class = true, 65 | Short('t') | Long("prefix-type") => c.settings.prefix_type = true, 66 | Long("expand-opt") => c.settings.expand_opt = true, 67 | Value(val) => { 68 | let file = PathBuf::from(&val); 69 | if !file.is_file() { 70 | return Err(lexopt::Error::UnexpectedArgument(OsString::from(format!( 71 | "{} is not a file!", 72 | file.display() 73 | )))); 74 | } 75 | c.files.push(file) 76 | } 77 | _ => return Err(arg.unexpected()), 78 | } 79 | } 80 | 81 | Ok(c) 82 | } 83 | 84 | pub fn run(self) { 85 | let mut vimcats = VimCats::new(); 86 | 87 | for f in self.files { 88 | let source = read_to_string(f).unwrap(); 89 | vimcats.for_help(&source, &self.settings).unwrap(); 90 | } 91 | 92 | print!("{}", VimDoc::from_emmy(&vimcats, &self.settings)); 93 | 94 | if self.modeline { 95 | println!("vim:tw=78:ts=8:noet:ft=help:norl:"); 96 | } 97 | } 98 | 99 | #[inline] 100 | pub fn help() { 101 | print!( 102 | r#"{NAME} {VERSION} 103 | {AUTHOR} 104 | {DESC} 105 | 106 | USAGE: 107 | {NAME} [FLAGS] [OPTIONS] ... 108 | 109 | ARGS: 110 | ... Path to lua files 111 | 112 | FLAGS: 113 | -h, --help Print help information 114 | -v, --version Print version information 115 | -M, --no-modeline Don't print modeline at the end 116 | -f, --prefix-func Prefix function name with ---@mod name 117 | -a, --prefix-alias Prefix ---@alias tag with return/---@mod name 118 | -c, --prefix-class Prefix ---@class tag with return/---@mod name 119 | -t, --prefix-type Prefix ---@type tag with ---@mod name 120 | --expand-opt Expand '?' (optional) to 'nil' type 121 | 122 | OPTIONS: 123 | -i, --indent Controls the indent width [default: 4] 124 | -l, --layout Vimdoc text layout [default: 'default'] 125 | - "default" : Default layout 126 | - "compact[:n=0]" : Aligns [desc] with 127 | and uses {{n}}, if provided, to indent the 128 | following new lines. This option only 129 | affects ---@field and ---@param tags 130 | - "mini[:n=0]" : Aligns [desc] from the start 131 | and uses {{n}}, if provided, to indent the 132 | following new lines. This option affects 133 | ---@field, ---@param and ---@return tags 134 | 135 | USAGE: 136 | {NAME} /path/to/first.lua /path/to/second.lua > doc/PLUGIN_NAME.txt 137 | {NAME} -c -a /path/to/{{first,second,third}}.lua > doc/PLUGIN_NAME.txt 138 | {NAME} --layout compact:2 /path/to/plugin.lua > doc/PLUGIN_NAME.txt 139 | 140 | NOTES: 141 | - The order of parsing + rendering is relative to the given files 142 | "# 143 | ); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/lexer.rs: -------------------------------------------------------------------------------- 1 | mod token; 2 | pub use token::*; 3 | 4 | use std::ops::Range; 5 | 6 | use chumsky::{ 7 | prelude::{any, choice, end, filter, just, take_until, Simple}, 8 | recursive::recursive, 9 | text::{ident, keyword, newline, whitespace, TextParser}, 10 | Parser, 11 | }; 12 | 13 | type Spanned = (TagType, Range); 14 | 15 | const C: [char; 3] = ['.', '_', '-']; 16 | 17 | #[derive(Debug)] 18 | pub struct Lexer; 19 | 20 | impl Lexer { 21 | /// Parse luaCATS/lua files into rust token 22 | pub fn init() -> impl Parser, Error = Simple> { 23 | let triple = just("---"); 24 | let space = just(' ').repeated().at_least(1); 25 | let comma = just(',').padded(); 26 | let till_eol = take_until(newline()); 27 | 28 | let comment = till_eol.map(|(x, _)| x.iter().collect()); 29 | let desc = space.ignore_then(comment).or_not(); 30 | 31 | let public = keyword("public").to(Scope::Public); 32 | let private = keyword("private") 33 | .to(Scope::Private) 34 | .or(keyword("protected").to(Scope::Protected)) 35 | .or(keyword("package").to(Scope::Package)); 36 | let exact_attr = just("(exact)"); 37 | 38 | let hidden = private 39 | .clone() 40 | .ignore_then(newline()) 41 | .then_ignore(choice(( 42 | // eat up all the emmylua, if any, then one valid token 43 | triple 44 | .then(till_eol) 45 | .padded() 46 | .repeated() 47 | .ignore_then(ident()), 48 | // if there is no emmylua, just eat the next token 49 | // so the next parser won't recognize the code 50 | ident().padded(), 51 | ))) 52 | .ignored(); 53 | 54 | let union_literal = choice(( 55 | just('\'') 56 | .ignore_then(filter(|c| c != &'\'').repeated()) 57 | .then_ignore(just('\'')) 58 | .collect() 59 | .map(Member::Literal), 60 | just('`') 61 | .ignore_then(filter(|c| c != &'`').repeated()) 62 | .then_ignore(just('`')) 63 | .collect() 64 | .map(Member::Ident), 65 | )); 66 | 67 | let variant = just('|') 68 | .then_ignore(space) 69 | .ignore_then(union_literal) 70 | .then( 71 | space 72 | .ignore_then(just('#').ignore_then(space).ignore_then(comment)) 73 | .or_not(), 74 | ) 75 | .map(|(t, d)| TagType::Variant(t, d)); 76 | 77 | let optional = just('?').or_not().map(|c| match c { 78 | Some(_) => Name::Opt as fn(_) -> _, 79 | None => Name::Req as fn(_) -> _, 80 | }); 81 | 82 | let name = filter(|x: &char| x.is_alphanumeric() || C.contains(x)) 83 | .repeated() 84 | .collect(); 85 | 86 | let names = name 87 | .separated_by(comma) 88 | .collect::>() 89 | .map(|items| items.join(", ")) 90 | .or(name); 91 | 92 | let ty = recursive(|inner| { 93 | let colon = just(':').padded(); 94 | 95 | let any = just("any").to(Ty::Any); 96 | let unknown = just("unknown").to(Ty::Unknown); 97 | let nil = just("nil").to(Ty::Nil); 98 | let boolean = just("boolean").to(Ty::Boolean); 99 | let string = just("string").to(Ty::String); 100 | let num = just("number").to(Ty::Number); 101 | let int = just("integer").to(Ty::Integer); 102 | let function = just("function").to(Ty::Function); 103 | let thread = just("thread").to(Ty::Thread); 104 | let userdata = just("userdata").to(Ty::Userdata); 105 | let lightuserdata = just("lightuserdata").to(Ty::Lightuserdata); 106 | 107 | #[inline] 108 | fn array_union( 109 | p: impl Parser>, 110 | inner: impl Parser>, 111 | ) -> impl Parser> { 112 | p.then(just("[]").repeated()) 113 | .foldl(|arr, _| Ty::Array(Box::new(arr))) 114 | // NOTE: Not the way I wanted i.e., Ty::Union(Vec) it to be, but it's better than nothing 115 | .then(just('|').padded().ignore_then(inner).repeated()) 116 | .foldl(|x, y| Ty::Union(Box::new(x), Box::new(y))) 117 | } 118 | 119 | let list_like = ident() 120 | .padded() 121 | .then(optional) 122 | .then( 123 | colon 124 | .ignore_then(inner.clone()) 125 | .or_not() 126 | // NOTE: if param type is missing then LLS treats it as `any` 127 | .map(|x| x.unwrap_or(Ty::Any)), 128 | ) 129 | .map(|((n, attr), t)| (attr(n), t)) 130 | .separated_by(comma) 131 | .allow_trailing(); 132 | 133 | let fun = just("fun") 134 | .ignore_then( 135 | list_like 136 | .clone() 137 | .delimited_by(just('(').then(whitespace()), whitespace().then(just(')'))), 138 | ) 139 | .then( 140 | colon 141 | .ignore_then(inner.clone().separated_by(comma)) 142 | .or_not(), 143 | ) 144 | .map(|(param, ret)| Ty::Fun(param, ret)); 145 | 146 | let table = just("table") 147 | .ignore_then( 148 | just('<') 149 | .ignore_then(inner.clone().map(Box::new)) 150 | .then_ignore(comma) 151 | .then(inner.clone().map(Box::new)) 152 | .then_ignore(just('>')) 153 | .or_not(), 154 | ) 155 | .map(Ty::Table); 156 | 157 | let dict = list_like 158 | .delimited_by(just('{').then(whitespace()), whitespace().then(just('}'))) 159 | .map(Ty::Dict); 160 | 161 | let ty_name = name.map(Ty::Ref); 162 | 163 | let parens = inner 164 | .clone() 165 | .delimited_by(just('(').padded(), just(')').padded()); 166 | 167 | // Union of string literals: '"g@"'|'"g@$"' 168 | let string_literal = union_literal.map(Ty::Member); 169 | 170 | choice(( 171 | array_union(any, inner.clone()), 172 | array_union(unknown, inner.clone()), 173 | array_union(nil, inner.clone()), 174 | array_union(boolean, inner.clone()), 175 | array_union(string, inner.clone()), 176 | array_union(num, inner.clone()), 177 | array_union(int, inner.clone()), 178 | array_union(function, inner.clone()), 179 | array_union(thread, inner.clone()), 180 | array_union(userdata, inner.clone()), 181 | array_union(lightuserdata, inner.clone()), 182 | array_union(fun, inner.clone()), 183 | array_union(table, inner.clone()), 184 | array_union(dict, inner.clone()), 185 | array_union(parens, inner.clone()), 186 | array_union(string_literal, inner.clone()), 187 | array_union(ty_name, inner), 188 | )) 189 | }); 190 | 191 | let numeric = filter(|x: &char| x.is_numeric()) 192 | .repeated() 193 | .collect::(); 194 | let code_lang = ident().then_ignore(space).or_not(); 195 | let generic_ident = just('[').ignore_then(ident()).then_ignore(just(']')); 196 | let list_index = just('[').ignore_then(numeric).then_ignore(just(']')); 197 | 198 | let tag = just('@').ignore_then(choice(( 199 | hidden.or(public.clone().ignored()).to(TagType::Skip), 200 | just("toc") 201 | .ignore_then(space) 202 | .ignore_then(comment) 203 | .map(TagType::Toc), 204 | just("mod") 205 | .then_ignore(space) 206 | .ignore_then(name) 207 | .then(desc) 208 | .map(|(name, desc)| TagType::Module(name, desc)), 209 | just("divider") 210 | .ignore_then(space) 211 | .ignore_then(any()) 212 | .map(TagType::Divider), 213 | just("brief").ignore_then(space).ignore_then(choice(( 214 | just("[[").to(TagType::BriefStart), 215 | just("]]").to(TagType::BriefEnd), 216 | ))), 217 | just("param") 218 | .ignore_then(space) 219 | .ignore_then(choice(( 220 | just("...").map(|n| Name::Req(n.to_string())), 221 | ident().then(optional).map(|(n, o)| o(n)), 222 | ))) 223 | .then_ignore(space) 224 | .then(ty.clone()) 225 | .then(desc) 226 | .map(|((name, ty), desc)| TagType::Param(name, ty, desc)), 227 | just("return") 228 | .ignore_then(space) 229 | .ignore_then(ty.clone()) 230 | .then(choice(( 231 | newline().to((None, None)), 232 | space.ignore_then(choice(( 233 | just('#').ignore_then(comment).map(|x| (None, Some(x))), 234 | ident().then(desc).map(|(name, desc)| (Some(name), desc)), 235 | ))), 236 | ))) 237 | .map(|(ty, (name, desc))| TagType::Return(ty, name, desc)), 238 | just("class") 239 | .ignore_then(space.ignore_then((exact_attr.ignore_then(space)).or_not())) 240 | .ignore_then(name) 241 | .then(just(':').padded().ignore_then(names).or_not()) 242 | .map(|(name, parent)| TagType::Class(name, parent)), 243 | just("field") 244 | .ignore_then(space.ignore_then(private.or(public)).or_not()) 245 | .then_ignore(space) 246 | .then(ident().or(generic_ident).or(list_index)) 247 | .then(optional) 248 | .then_ignore(space) 249 | .then(ty.clone()) 250 | .then(desc) 251 | .map(|((((scope, name), opt), ty), desc)| { 252 | TagType::Field(scope.unwrap_or(Scope::Public), opt(name), ty, desc) 253 | }), 254 | just("enum") 255 | .ignore_then(name.padded()) 256 | .then_ignore(till_eol) // table declaration, e.g. `local MyEnum = {` 257 | .map(TagType::Enum), 258 | just("alias") 259 | .ignore_then(space) 260 | .ignore_then(name) 261 | .then(space.ignore_then(ty.clone()).or_not()) 262 | .map(|(name, ty)| TagType::Alias(name, ty)), 263 | just("type") 264 | .ignore_then(space) 265 | .ignore_then(ty) 266 | .then(desc) 267 | .map(|(ty, desc)| TagType::Type(ty, desc)), 268 | just("tag") 269 | .ignore_then(space) 270 | .ignore_then(comment) 271 | .map(TagType::Tag), 272 | just("see") 273 | .ignore_then(space) 274 | .ignore_then(comment) 275 | .map(TagType::See), 276 | just("usage").ignore_then(space).ignore_then(choice(( 277 | code_lang 278 | .then( 279 | just('`') 280 | .ignore_then(filter(|c| *c != '`').repeated()) 281 | .then_ignore(just('`')) 282 | .collect(), 283 | ) 284 | .map(|(lang, code)| TagType::Usage(lang, code)), 285 | code_lang.then_ignore(just("[[")).map(TagType::UsageStart), 286 | just("]]").to(TagType::UsageEnd), 287 | ))), 288 | just("export") 289 | .ignore_then(space) 290 | .ignore_then(ident()) 291 | .then_ignore(take_until(end())) 292 | .map(TagType::Export), 293 | ))); 294 | 295 | let func = keyword("function").padded(); 296 | let ret = keyword("return"); 297 | let assign = just('=').padded(); 298 | 299 | // obj = ID (prop)+ "=" 300 | // fn = ID (prop | colon_op) 301 | // prop = (dot_op)+ ("(" | colon_op) 302 | // dot_op = "." ID 303 | // colon_op = ":" ID "(" 304 | let colon_op = just(':') 305 | .ignore_then(ident()) 306 | .then_ignore(just('(')) 307 | .map(Op::Colon); 308 | 309 | let dot_op = just('.') 310 | .ignore_then(ident().map(Op::Dot)) 311 | .repeated() 312 | .at_least(1); 313 | 314 | let prop = dot_op 315 | .then(choice((just('(').to(None), colon_op.map(Some)))) 316 | .map(|(mut props, meth)| { 317 | if let Some(x) = meth { 318 | props.push(x) 319 | } 320 | Op::Deep(props) 321 | }); 322 | 323 | let dotted = ident() 324 | .then(choice((prop, colon_op))) 325 | .map(|(prefix, op)| (prefix, op)); 326 | 327 | let expr = ident().then(dot_op).then_ignore(assign); 328 | let variable = ident().then_ignore(assign).then_ignore(till_eol.or_not()); 329 | 330 | choice(( 331 | triple.ignore_then(choice((tag, variant, comment.map(TagType::Comment)))), 332 | func.clone() 333 | .ignore_then(dotted) 334 | .map(|(prefix, op)| TagType::Func(prefix, op)), 335 | expr.then(func.or_not()) 336 | .map(|((prefix, op), is_fn)| match is_fn { 337 | Some(_) => TagType::Func(prefix, Op::Deep(op)), 338 | None => TagType::Expr(prefix, Op::Deep(op)), 339 | }), 340 | variable.map(TagType::Variable), 341 | ret.ignore_then(ident().padded()) 342 | .then_ignore(end()) 343 | .map(TagType::Export), 344 | till_eol.to(TagType::Skip), 345 | )) 346 | .padded() 347 | .map_with_span(|t, r| (t, r)) 348 | .repeated() 349 | } 350 | } 351 | -------------------------------------------------------------------------------- /src/lexer/token.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 4 | pub enum Member { 5 | Literal(String), 6 | Ident(String), 7 | } 8 | 9 | impl Display for Member { 10 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 11 | match self { 12 | Self::Literal(lit) => f.write_str(&format!( 13 | r#""{}""#, 14 | lit.trim_start_matches('"').trim_end_matches('"') 15 | )), 16 | Self::Ident(ident) => f.write_str(ident), 17 | } 18 | } 19 | } 20 | 21 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 22 | pub enum TagType { 23 | /// ```lua 24 | /// ---@toc 25 | /// ``` 26 | Toc(String), 27 | /// ```lua 28 | /// ---@mod [desc] 29 | /// ``` 30 | Module(String, Option), 31 | /// ```lua 32 | /// ---@divider 33 | /// ``` 34 | Divider(char), 35 | /// ```lua 36 | /// function one.two() end 37 | /// one.two = function() end 38 | /// ``` 39 | Func(String, Op), 40 | /// ```lua 41 | /// one = 1 42 | /// one.two = 12 43 | /// ``` 44 | Expr(String, Op), 45 | /// ```lua 46 | /// ---@export 47 | /// or 48 | /// return \eof 49 | /// ``` 50 | Export(String), 51 | /// ```lua 52 | /// ---@brief [[ 53 | /// ``` 54 | BriefStart, 55 | /// ```lua 56 | /// ---@brief ]] 57 | /// ``` 58 | BriefEnd, 59 | /// ```lua 60 | /// ---@param [description] 61 | /// ``` 62 | Param(Name, Ty, Option), 63 | /// ```lua 64 | /// ---@return [ [comment] | [name] #] 65 | /// ``` 66 | Return(Ty, Option, Option), 67 | /// ```lua 68 | /// ---@class [: ] 69 | /// ``` 70 | Class(String, Option), 71 | /// ```lua 72 | /// ---@field [public|private|protected] [description] 73 | /// ``` 74 | Field(Scope, Name, Ty, Option), 75 | /// ```lua 76 | /// = 77 | /// ``` 78 | Variable(String), 79 | /// ```lua 80 | /// ---@enum 81 | /// ``` 82 | Enum(String), 83 | /// ```lua 84 | /// -- Simple Alias 85 | /// ---@alias 86 | /// 87 | /// -- Enum alias 88 | /// ---@alias 89 | /// ``` 90 | Alias(String, Option), 91 | /// ```lua 92 | /// ---| '' [# description] 93 | /// 94 | /// -- or 95 | /// 96 | /// ---| `` [# description] 97 | /// ``` 98 | Variant(Member, Option), 99 | /// ```lua 100 | /// ---@type [desc] 101 | /// ``` 102 | Type(Ty, Option), 103 | /// ```lua 104 | /// ---@tag 105 | /// ``` 106 | Tag(String), 107 | /// ```lua 108 | /// ---@see 109 | /// ``` 110 | See(String), 111 | /// ```lua 112 | /// ---@usage [lang] `` 113 | /// ``` 114 | Usage(Option, String), 115 | /// ```lua 116 | /// ---@usage [lang] [[ 117 | /// ``` 118 | UsageStart(Option), 119 | /// ```lua 120 | /// ---@usage ]] 121 | /// ``` 122 | UsageEnd, 123 | /// ```lua 124 | /// ---TEXT 125 | /// ``` 126 | Comment(String), 127 | /// Text nodes which are not needed 128 | Skip, 129 | } 130 | 131 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 132 | pub enum Op { 133 | Deep(Vec), 134 | Dot(String), 135 | Colon(String), 136 | } 137 | 138 | impl Display for Op { 139 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 140 | match self { 141 | Self::Deep(mixed) => { 142 | for mix in mixed { 143 | mix.fmt(f)?; 144 | } 145 | Ok(()) 146 | } 147 | Self::Dot(dot) => { 148 | f.write_str(".")?; 149 | f.write_str(dot) 150 | } 151 | Self::Colon(colon) => { 152 | f.write_str(":")?; 153 | f.write_str(colon) 154 | } 155 | } 156 | } 157 | } 158 | 159 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 160 | pub enum Scope { 161 | Public, 162 | Private, 163 | Protected, 164 | Package, 165 | } 166 | 167 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 168 | pub enum Name { 169 | Req(String), 170 | Opt(String), 171 | } 172 | 173 | impl Display for Name { 174 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 175 | match self { 176 | Self::Req(n) => f.write_str(n), 177 | Self::Opt(n) => { 178 | f.write_str(n)?; 179 | f.write_str("?") 180 | } 181 | } 182 | } 183 | } 184 | 185 | // Source: https://github.com/sumneko/lua-language-server/wiki/Annotations#documenting-types 186 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 187 | pub enum Ty { 188 | Nil, 189 | Any, 190 | Unknown, 191 | Boolean, 192 | String, 193 | Number, 194 | Integer, 195 | Function, 196 | Thread, 197 | Userdata, 198 | Lightuserdata, 199 | Ref(String), 200 | Member(Member), 201 | Array(Box), 202 | Table(Option<(Box, Box)>), 203 | Fun(Vec<(Name, Ty)>, Option>), 204 | Dict(Vec<(Name, Ty)>), 205 | Union(Box, Box), 206 | } 207 | 208 | impl Display for Ty { 209 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 210 | fn list_like(args: &[(Name, Ty)]) -> String { 211 | args.iter() 212 | .map(|(n, t)| format!("{n}:{t}")) 213 | .collect::>() 214 | .join(",") 215 | } 216 | 217 | match self { 218 | Self::Nil => f.write_str("nil"), 219 | Self::Any => f.write_str("any"), 220 | Self::Unknown => f.write_str("unknown"), 221 | Self::Boolean => f.write_str("boolean"), 222 | Self::String => f.write_str("string"), 223 | Self::Number => f.write_str("number"), 224 | Self::Integer => f.write_str("integer"), 225 | Self::Function => f.write_str("function"), 226 | Self::Thread => f.write_str("thread"), 227 | Self::Userdata => f.write_str("userdata"), 228 | Self::Lightuserdata => f.write_str("lightuserdata"), 229 | Self::Ref(id) => f.write_str(id), 230 | Self::Array(ty) => { 231 | f.write_str(&ty.to_string())?; 232 | f.write_str("[]") 233 | } 234 | Self::Table(kv) => match kv { 235 | Some((k, v)) => { 236 | f.write_str("table<")?; 237 | f.write_str(&k.to_string())?; 238 | f.write_str(",")?; 239 | f.write_str(&v.to_string())?; 240 | f.write_str(">") 241 | } 242 | None => f.write_str("table"), 243 | }, 244 | Self::Fun(args, ret) => { 245 | f.write_str("fun(")?; 246 | f.write_str(&list_like(args))?; 247 | f.write_str(")")?; 248 | if let Some(ret) = ret { 249 | f.write_str(":")?; 250 | f.write_str( 251 | &ret.iter() 252 | .map(|r| r.to_string()) 253 | .collect::>() 254 | .join(","), 255 | )?; 256 | } 257 | Ok(()) 258 | } 259 | Self::Dict(kv) => { 260 | f.write_str("{")?; 261 | f.write_str(&list_like(kv))?; 262 | f.write_str("}") 263 | } 264 | Self::Union(rhs, lhs) => { 265 | f.write_str(&rhs.to_string())?; 266 | f.write_str("|")?; 267 | f.write_str(&lhs.to_string()) 268 | } 269 | Self::Member(mem) => mem.fmt(f), 270 | } 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "vimdoc")] 2 | pub mod vimdoc; 3 | 4 | pub mod lexer; 5 | pub mod parser; 6 | 7 | use std::{fmt::Display, str::FromStr}; 8 | 9 | use chumsky::prelude::Simple; 10 | 11 | use parser::{ 12 | Alias, Brief, Class, Divider, Enum, EnumValue, Field, Func, Module, Node, Param, Return, See, 13 | Tag, Type, Usage, 14 | }; 15 | 16 | use crate::lexer::TagType; 17 | 18 | pub trait Visitor { 19 | type R; 20 | type S; 21 | fn module(&self, n: &Module, s: &Self::S) -> Self::R; 22 | fn divider(&self, n: &Divider, s: &Self::S) -> Self::R; 23 | fn brief(&self, n: &Brief, s: &Self::S) -> Self::R; 24 | fn tag(&self, n: &Tag, s: &Self::S) -> Self::R; 25 | fn func(&self, n: &Func, s: &Self::S) -> Self::R; 26 | fn params(&self, n: &[Param], s: &Self::S) -> Self::R; 27 | fn r#returns(&self, n: &[Return], s: &Self::S) -> Self::R; 28 | fn class(&self, n: &Class, s: &Self::S) -> Self::R; 29 | fn fields(&self, n: &[Field], s: &Self::S) -> Self::R; 30 | fn r#enum(&self, n: &Enum, s: &Self::S) -> Self::R; 31 | fn enum_values(&self, n: &[EnumValue], s: &Self::S) -> Self::R; 32 | fn alias(&self, n: &Alias, s: &Self::S) -> Self::R; 33 | fn r#type(&self, n: &Type, s: &Self::S) -> Self::R; 34 | fn toc(&self, n: &str, nodes: &[Node], s: &Self::S) -> Self::R; 35 | fn see(&self, n: &See, s: &Self::S) -> Self::R; 36 | fn usage(&self, n: &Usage, s: &Self::S) -> Self::R; 37 | } 38 | 39 | pub trait Accept { 40 | fn accept(&self, n: &T, s: &T::S) -> T::R; 41 | } 42 | 43 | pub trait Nodes { 44 | fn nodes(&self) -> &Vec; 45 | } 46 | 47 | pub trait FromLuaCATS: Display { 48 | type Settings; 49 | fn from_emmy(t: &impl Nodes, s: &Self::Settings) -> Self; 50 | } 51 | 52 | pub trait AsDoc { 53 | fn as_doc(&self, s: &T::Settings) -> T; 54 | } 55 | 56 | #[derive(Debug, Default, PartialEq, Eq)] 57 | pub enum Layout { 58 | #[default] 59 | Default, 60 | Compact(u8), 61 | Mini(u8), 62 | } 63 | 64 | impl FromStr for Layout { 65 | type Err = (); 66 | fn from_str(s: &str) -> Result { 67 | match s { 68 | "default" => Ok(Self::Default), 69 | x => { 70 | let mut val = x.splitn(2, ':'); 71 | match (val.next(), val.next()) { 72 | (Some("compact"), n) => Ok(Self::Compact( 73 | n.map_or(0, |x| x.parse().unwrap_or_default()), 74 | )), 75 | (Some("mini"), n) => { 76 | Ok(Self::Mini(n.map_or(0, |x| x.parse().unwrap_or_default()))) 77 | } 78 | _ => Err(()), 79 | } 80 | } 81 | } 82 | } 83 | } 84 | 85 | #[derive(Debug)] 86 | pub struct Settings { 87 | /// Prefix `function` name with `---@mod` name 88 | pub prefix_func: bool, 89 | /// Prefix `---@alias` tag with `---@mod/return` name 90 | pub prefix_alias: bool, 91 | /// Prefix `---@class` tag with `---@mod/return` name 92 | pub prefix_class: bool, 93 | /// Prefix `---@type` tag with `---@mod` name 94 | pub prefix_type: bool, 95 | /// Expand `?` to `nil|` 96 | pub expand_opt: bool, 97 | /// Vimdoc text layout 98 | pub layout: Layout, 99 | /// Controls the indent width 100 | pub indent_width: usize, 101 | } 102 | 103 | impl Default for Settings { 104 | fn default() -> Self { 105 | Self { 106 | prefix_func: false, 107 | prefix_alias: false, 108 | prefix_class: false, 109 | prefix_type: false, 110 | expand_opt: false, 111 | layout: Layout::default(), 112 | indent_width: 4, 113 | } 114 | } 115 | } 116 | 117 | #[derive(Debug, Default)] 118 | pub struct VimCats { 119 | nodes: Vec, 120 | } 121 | 122 | impl Nodes for VimCats { 123 | fn nodes(&self) -> &Vec { 124 | &self.nodes 125 | } 126 | } 127 | 128 | impl AsDoc for VimCats { 129 | fn as_doc(&self, s: &T::Settings) -> T { 130 | T::from_emmy(self, s) 131 | } 132 | } 133 | 134 | impl VimCats { 135 | /// Creates a new parser instance 136 | /// 137 | /// ``` 138 | /// use vimcats::VimCats; 139 | /// 140 | /// VimCats::new(); 141 | /// ``` 142 | pub fn new() -> Self { 143 | Self { nodes: vec![] } 144 | } 145 | 146 | /// Parse given lua source code to generate AST representation 147 | /// 148 | /// ``` 149 | /// use vimcats::{VimCats, Nodes}; 150 | /// 151 | /// let mut vimcats = VimCats::default(); 152 | /// let src = r#" 153 | /// local U = {} 154 | /// 155 | /// ---Add two integar and print it 156 | /// ---@param this number First number 157 | /// ---@param that number Second number 158 | /// function U.sum(this, that) 159 | /// print(this + that) 160 | /// end 161 | /// 162 | /// return U 163 | /// "#; 164 | /// 165 | /// let ast = vimcats.parse(&src).unwrap(); 166 | /// assert!(!ast.nodes().is_empty()); 167 | /// ``` 168 | pub fn parse(&mut self, src: &str) -> Result<&Self, Vec>> { 169 | self.nodes.append(&mut Node::new(src)?); 170 | 171 | Ok(self) 172 | } 173 | 174 | /// Similar to [`VimCats::parse`], but specifically used for generating vimdoc 175 | pub fn for_help( 176 | &mut self, 177 | src: &str, 178 | settings: &Settings, 179 | ) -> Result<&Self, Vec>> { 180 | let mut nodes = Node::new(src)?; 181 | 182 | if let Some(Node::Export(export)) = nodes.pop() { 183 | let module = match nodes.iter().rev().find(|x| matches!(x, Node::Module(_))) { 184 | Some(Node::Module(m)) => m.name.to_owned(), 185 | _ => export.to_owned(), 186 | }; 187 | 188 | for ele in nodes { 189 | match ele { 190 | Node::Export(..) => {} 191 | Node::Func(mut func) => { 192 | if func.prefix.left.as_deref() == Some(&export) { 193 | if settings.prefix_func { 194 | func.prefix.right = Some(module.to_owned()); 195 | } 196 | self.nodes.push(Node::Func(func)); 197 | } 198 | } 199 | Node::Type(mut typ) => { 200 | if typ.prefix.left.as_deref() == Some(&export) { 201 | if settings.prefix_type { 202 | typ.prefix.right = Some(module.to_owned()); 203 | } 204 | self.nodes.push(Node::Type(typ)); 205 | } 206 | } 207 | Node::Alias(mut alias) => { 208 | if settings.prefix_alias { 209 | alias.prefix.right = Some(module.to_owned()); 210 | } 211 | self.nodes.push(Node::Alias(alias)) 212 | } 213 | Node::Class(mut class) => { 214 | if settings.prefix_class { 215 | class.prefix.right = Some(module.to_owned()); 216 | } 217 | self.nodes.push(Node::Class(class)) 218 | } 219 | _ => self.nodes.push(ele), 220 | } 221 | } 222 | }; 223 | 224 | Ok(self) 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod cli; 2 | 3 | use std::process::exit; 4 | 5 | use cli::Cli; 6 | 7 | fn main() { 8 | match Cli::new() { 9 | Ok(c) => c.run(), 10 | Err(e) => { 11 | eprintln!("{e}"); 12 | exit(1) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | mod node; 2 | pub use node::*; 3 | mod tags; 4 | pub use tags::*; 5 | 6 | macro_rules! impl_parse { 7 | ($id: ident, $ret: ty, $body: expr) => { 8 | impl $id { 9 | pub fn parse() -> impl chumsky::Parser< 10 | $crate::lexer::TagType, 11 | $ret, 12 | Error = chumsky::prelude::Simple<$crate::lexer::TagType>, 13 | > { 14 | $body 15 | } 16 | } 17 | }; 18 | ($id: ident, $body: expr) => { 19 | crate::parser::impl_parse!($id, Self, $body); 20 | }; 21 | } 22 | 23 | pub(super) use impl_parse; 24 | -------------------------------------------------------------------------------- /src/parser/node.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{ 2 | prelude::{any, choice, Simple}, 3 | select, Parser, Stream, 4 | }; 5 | 6 | use crate::{ 7 | lexer::{Lexer, TagType}, 8 | parser::{Alias, Brief, Class, Divider, Enum, Func, Module, Tag, Type}, 9 | Accept, Visitor, 10 | }; 11 | 12 | use super::impl_parse; 13 | 14 | #[derive(Debug, Clone)] 15 | pub enum Node { 16 | Module(Module), 17 | Divider(Divider), 18 | Brief(Brief), 19 | Tag(Tag), 20 | Func(Func), 21 | Class(Class), 22 | Enum(Enum), 23 | Alias(Alias), 24 | Type(Type), 25 | Export(String), 26 | Toc(String), 27 | } 28 | 29 | impl_parse!(Node, Option, { 30 | choice(( 31 | Module::parse().map(Self::Module), 32 | Divider::parse().map(Self::Divider), 33 | Brief::parse().map(Self::Brief), 34 | Tag::parse().map(Self::Tag), 35 | Func::parse().map(Self::Func), 36 | Class::parse().map(Self::Class), 37 | Enum::parse().map(Self::Enum), 38 | Alias::parse().map(Self::Alias), 39 | Type::parse().map(Self::Type), 40 | select! { 41 | TagType::Export(x) => Self::Export(x), 42 | TagType::Toc(x) => Self::Toc(x), 43 | }, 44 | )) 45 | .map(Some) 46 | // Skip useless nodes 47 | .or(any().to(None)) 48 | }); 49 | 50 | impl Accept for Node { 51 | fn accept(&self, n: &T, s: &T::S) -> T::R { 52 | match self { 53 | Self::Brief(x) => x.accept(n, s), 54 | Self::Tag(x) => x.accept(n, s), 55 | Self::Enum(x) => x.accept(n, s), 56 | Self::Alias(x) => x.accept(n, s), 57 | Self::Func(x) => x.accept(n, s), 58 | Self::Class(x) => x.accept(n, s), 59 | Self::Type(x) => x.accept(n, s), 60 | Self::Module(x) => x.accept(n, s), 61 | Self::Divider(x) => x.accept(n, s), 62 | _ => unimplemented!(), 63 | } 64 | } 65 | } 66 | 67 | impl Node { 68 | fn init() -> impl Parser, Error = Simple> { 69 | Node::parse().repeated().flatten() 70 | } 71 | 72 | /// Creates stream of AST nodes from emmylua 73 | /// 74 | /// ``` 75 | /// let src = r#" 76 | /// local U = {} 77 | /// 78 | /// ---Add two integar and print it 79 | /// ---@param this number First number 80 | /// ---@param that number Second number 81 | /// function U.sum(this, that) 82 | /// print(this + that) 83 | /// end 84 | /// 85 | /// return U 86 | /// "#; 87 | /// 88 | /// let nodes = vimcats::parser::Node::new(src).unwrap(); 89 | /// assert!(!nodes.is_empty()); 90 | /// ``` 91 | pub fn new(src: &str) -> Result, Vec>> { 92 | let tokens = Lexer::init().parse(src).unwrap(); 93 | let stream = Stream::from_iter(src.len()..src.len() + 1, tokens.into_iter()); 94 | 95 | Node::init().parse(stream) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/parser/tags/alias.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{prelude::choice, select, Parser}; 2 | 3 | use crate::{ 4 | lexer::{Member, TagType, Ty}, 5 | parser::{impl_parse, Prefix}, 6 | Accept, Visitor, 7 | }; 8 | 9 | #[derive(Debug, Clone)] 10 | pub enum AliasKind { 11 | Type(Ty), 12 | Enum(Vec<(Member, Option)>), 13 | } 14 | 15 | #[derive(Debug, Clone)] 16 | pub struct Alias { 17 | pub name: String, 18 | pub desc: Vec, 19 | pub kind: AliasKind, 20 | pub prefix: Prefix, 21 | } 22 | 23 | impl_parse!(Alias, { 24 | select! { 25 | TagType::Comment(x) => x, 26 | } 27 | .repeated() 28 | .then(choice(( 29 | select! { 30 | TagType::Alias(name, Some(ty)) => (name, AliasKind::Type(ty)) 31 | }, 32 | select! { TagType::Alias(name, ..) => name }.then( 33 | select! { 34 | TagType::Variant(ty, desc) => (ty, desc) 35 | } 36 | .repeated() 37 | .map(AliasKind::Enum), 38 | ), 39 | ))) 40 | .map(|(desc, (name, kind))| Self { 41 | name, 42 | desc, 43 | kind, 44 | prefix: Prefix::default(), 45 | }) 46 | }); 47 | 48 | impl Accept for Alias { 49 | fn accept(&self, n: &T, s: &T::S) -> T::R { 50 | n.alias(self, s) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/parser/tags/brief.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{prelude::just, select, Parser}; 2 | 3 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct Brief { 7 | pub desc: Vec, 8 | } 9 | 10 | impl_parse!(Brief, { 11 | select! { 12 | TagType::Comment(x) => x, 13 | } 14 | .repeated() 15 | .delimited_by(just(TagType::BriefStart), just(TagType::BriefEnd)) 16 | .map(|desc| Self { desc }) 17 | }); 18 | 19 | impl Accept for Brief { 20 | fn accept(&self, n: &T, s: &T::S) -> T::R { 21 | n.brief(self, s) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/parser/tags/class.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{select, Parser}; 2 | 3 | use crate::{ 4 | lexer::{Name, Scope, TagType, Ty}, 5 | parser::{impl_parse, Prefix, See}, 6 | Accept, Visitor, 7 | }; 8 | 9 | #[derive(Debug, Clone)] 10 | pub struct Field { 11 | pub scope: Scope, 12 | pub name: Name, 13 | pub ty: Ty, 14 | pub desc: Vec, 15 | } 16 | 17 | impl_parse!(Field, { 18 | select! { 19 | TagType::Comment(x) => x, 20 | } 21 | .repeated() 22 | .then(select! { 23 | TagType::Field(scope, name, ty, desc) => (scope, name, ty, desc) 24 | }) 25 | .map(|(header, (scope, name, ty, desc))| { 26 | let desc = match desc { 27 | Some(d) => { 28 | let mut new_desc = Vec::with_capacity(header.len() + 1); 29 | new_desc.push(d); 30 | new_desc.extend(header); 31 | new_desc 32 | } 33 | None => header, 34 | }; 35 | 36 | Self { 37 | scope, 38 | name, 39 | ty, 40 | desc, 41 | } 42 | }) 43 | }); 44 | 45 | #[derive(Debug, Clone)] 46 | pub struct Class { 47 | pub name: String, 48 | pub parent: Option, 49 | pub desc: Vec, 50 | pub fields: Vec, 51 | pub see: See, 52 | pub prefix: Prefix, 53 | } 54 | 55 | impl_parse!(Class, { 56 | select! { TagType::Comment(c) => c } 57 | .repeated() 58 | .then(select! { TagType::Class(name, parent) => (name, parent) }) 59 | .then(Field::parse().repeated()) 60 | .then(See::parse()) 61 | .map(|(((desc, (name, parent)), fields), see)| Self { 62 | name, 63 | parent, 64 | desc, 65 | fields, 66 | see, 67 | prefix: Prefix::default(), 68 | }) 69 | }); 70 | 71 | impl Accept for Class { 72 | fn accept(&self, n: &T, s: &T::S) -> T::R { 73 | n.class(self, s) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/parser/tags/divider.rs: -------------------------------------------------------------------------------- 1 | use chumsky::select; 2 | 3 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct Divider(pub char); 7 | 8 | impl_parse!(Divider, { 9 | select! { TagType::Divider(rune) => Self(rune) } 10 | }); 11 | 12 | impl Accept for Divider { 13 | fn accept(&self, n: &T, s: &T::S) -> T::R { 14 | n.divider(self, s) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/parser/tags/enum.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{select, Parser}; 2 | 3 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 4 | 5 | use super::See; 6 | 7 | #[derive(Debug, Clone)] 8 | pub struct Enum { 9 | pub name: String, 10 | pub values: Vec, 11 | pub desc: Vec, 12 | pub see: See, 13 | } 14 | 15 | #[derive(Debug, Clone)] 16 | pub struct EnumValue { 17 | pub name: String, 18 | pub desc: Vec, 19 | } 20 | 21 | impl_parse!(EnumValue, { 22 | select! { TagType::Comment(c) => c } 23 | .repeated() 24 | .then(select! { TagType::Variable(name) => name }) 25 | .map(|(desc, name)| Self { name, desc }) 26 | }); 27 | 28 | impl_parse!(Enum, { 29 | select! { TagType::Comment(c) => c } 30 | .repeated() 31 | .then(select! { TagType::Enum(name) => name }) 32 | .then(EnumValue::parse().repeated()) 33 | .then(See::parse()) 34 | .map(|(((desc, name), values), see)| Self { 35 | name, 36 | values, 37 | desc, 38 | see, 39 | }) 40 | }); 41 | 42 | impl Accept for Enum { 43 | fn accept(&self, n: &T, s: &T::S) -> T::R { 44 | n.r#enum(self, s) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/parser/tags/func.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{select, Parser}; 2 | 3 | use crate::{ 4 | lexer::{Name, Op, TagType, Ty}, 5 | parser::{impl_parse, Prefix, See}, 6 | Accept, Visitor, 7 | }; 8 | 9 | use super::Usage; 10 | 11 | #[derive(Debug, Clone)] 12 | pub struct Param { 13 | pub name: Name, 14 | pub ty: Ty, 15 | pub desc: Vec, 16 | } 17 | 18 | impl_parse!(Param, { 19 | select! { 20 | TagType::Param(name, ty, desc) => (name, ty, desc) 21 | } 22 | .then(select! { TagType::Comment(x) => x }.repeated()) 23 | .map(|((name, ty, desc), extra)| { 24 | let desc = match desc { 25 | Some(d) => { 26 | let mut new_desc = Vec::with_capacity(extra.len() + 1); 27 | new_desc.push(d); 28 | new_desc.extend(extra); 29 | new_desc 30 | } 31 | None => extra, 32 | }; 33 | Self { name, ty, desc } 34 | }) 35 | }); 36 | 37 | #[derive(Debug, Clone)] 38 | pub struct Return { 39 | pub ty: Ty, 40 | pub name: Option, 41 | pub desc: Vec, 42 | } 43 | 44 | impl_parse!(Return, { 45 | select! { 46 | TagType::Return(ty, name, desc) => (ty, name, desc) 47 | } 48 | .then(select! { TagType::Comment(x) => x }.repeated()) 49 | .map(|((ty, name, desc), extra)| { 50 | let desc = match desc { 51 | Some(d) => { 52 | let mut new_desc = Vec::with_capacity(extra.len() + 1); 53 | new_desc.push(d); 54 | new_desc.extend(extra); 55 | new_desc 56 | } 57 | None => extra, 58 | }; 59 | 60 | Self { name, ty, desc } 61 | }) 62 | }); 63 | 64 | #[derive(Debug, Clone)] 65 | pub struct Func { 66 | pub op: Op, 67 | pub prefix: Prefix, 68 | pub desc: Vec, 69 | pub params: Vec, 70 | pub returns: Vec, 71 | pub see: See, 72 | pub usage: Option, 73 | } 74 | 75 | impl_parse!(Func, { 76 | select! { 77 | TagType::Comment(x) => x, 78 | } 79 | .repeated() 80 | .then(Param::parse().repeated()) 81 | .then(Return::parse().repeated()) 82 | .then(See::parse()) 83 | .then(Usage::parse().or_not()) 84 | .then(select! { TagType::Func(prefix, op) => (prefix, op) }) 85 | .map( 86 | |(((((desc, params), returns), see), usage), (prefix, op))| Self { 87 | op, 88 | prefix: Prefix { 89 | left: Some(prefix.clone()), 90 | right: Some(prefix), 91 | }, 92 | desc, 93 | params, 94 | returns, 95 | see, 96 | usage, 97 | }, 98 | ) 99 | }); 100 | 101 | impl Accept for Func { 102 | fn accept(&self, n: &T, s: &T::S) -> T::R { 103 | n.func(self, s) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/parser/tags/mod.rs: -------------------------------------------------------------------------------- 1 | mod divider; 2 | pub use divider::*; 3 | mod r#enum; 4 | pub use r#enum::*; 5 | mod alias; 6 | pub use alias::*; 7 | mod brief; 8 | pub use brief::*; 9 | mod class; 10 | pub use class::*; 11 | mod func; 12 | pub use func::*; 13 | mod tag; 14 | pub use tag::*; 15 | mod r#type; 16 | pub use r#type::*; 17 | mod module; 18 | pub use module::*; 19 | mod see; 20 | pub use see::*; 21 | mod usage; 22 | pub use usage::*; 23 | 24 | #[derive(Debug, Default, Clone)] 25 | pub struct Prefix { 26 | pub left: Option, 27 | pub right: Option, 28 | } 29 | -------------------------------------------------------------------------------- /src/parser/tags/module.rs: -------------------------------------------------------------------------------- 1 | use chumsky::select; 2 | 3 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct Module { 7 | pub name: String, 8 | pub desc: Option, 9 | } 10 | 11 | impl_parse!(Module, { 12 | select! { TagType::Module(name, desc) => Self { name, desc } } 13 | }); 14 | 15 | impl Accept for Module { 16 | fn accept(&self, n: &T, s: &T::S) -> T::R { 17 | n.module(self, s) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/parser/tags/see.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{select, Parser}; 2 | 3 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct See { 7 | pub refs: Vec, 8 | } 9 | 10 | impl_parse!(See, { 11 | select! { TagType::See(x) => x } 12 | .repeated() 13 | .map(|refs| Self { refs }) 14 | }); 15 | 16 | impl Accept for See { 17 | fn accept(&self, n: &T, s: &T::S) -> T::R { 18 | n.see(self, s) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/parser/tags/tag.rs: -------------------------------------------------------------------------------- 1 | use chumsky::select; 2 | 3 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct Tag(pub String); 7 | 8 | impl_parse!(Tag, { 9 | select! { TagType::Tag(x) => Self(x) } 10 | }); 11 | 12 | impl Accept for Tag { 13 | fn accept(&self, n: &T, s: &T::S) -> T::R { 14 | n.tag(self, s) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/parser/tags/type.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{select, Parser}; 2 | 3 | use crate::{ 4 | lexer::{Op, TagType, Ty}, 5 | parser::{impl_parse, Prefix, See}, 6 | Accept, Visitor, 7 | }; 8 | 9 | use super::Usage; 10 | 11 | #[derive(Debug, Clone)] 12 | pub struct Type { 13 | pub desc: (Vec, Option), 14 | pub op: Op, 15 | pub prefix: Prefix, 16 | pub ty: Ty, 17 | pub see: See, 18 | pub usage: Option, 19 | } 20 | 21 | impl_parse!(Type, { 22 | select! { 23 | TagType::Comment(x) => x 24 | } 25 | .repeated() 26 | .then(select! { TagType::Type(ty, desc) => (ty, desc) }) 27 | .then(See::parse()) 28 | .then(Usage::parse().or_not()) 29 | .then(select! { TagType::Expr(prefix, op) => (prefix, op) }) 30 | .map( 31 | |((((extract, (ty, desc)), see), usage), (prefix, op))| Self { 32 | desc: (extract, desc), 33 | prefix: Prefix { 34 | left: Some(prefix.to_owned()), 35 | right: Some(prefix), 36 | }, 37 | op, 38 | ty, 39 | see, 40 | usage, 41 | }, 42 | ) 43 | }); 44 | 45 | impl Accept for Type { 46 | fn accept(&self, n: &T, s: &T::S) -> T::R { 47 | n.r#type(self, s) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/parser/tags/usage.rs: -------------------------------------------------------------------------------- 1 | use chumsky::{ 2 | primitive::{choice, just}, 3 | select, Parser, 4 | }; 5 | 6 | use crate::{lexer::TagType, parser::impl_parse, Accept, Visitor}; 7 | 8 | #[derive(Debug, Clone)] 9 | pub struct Usage { 10 | pub lang: Option, 11 | pub code: String, 12 | } 13 | 14 | impl_parse!(Usage, { 15 | choice(( 16 | select! { 17 | TagType::UsageStart(lang) => lang 18 | } 19 | .then(select! { TagType::Comment(x) => x }.repeated()) 20 | .then_ignore(just(TagType::UsageEnd)) 21 | .map(|(lang, code)| Self { 22 | lang, 23 | code: code.join("\n"), 24 | }), 25 | select! { 26 | TagType::Usage(lang, code) => Self { lang, code } 27 | }, 28 | )) 29 | }); 30 | 31 | impl Accept for Usage { 32 | fn accept(&self, n: &T, s: &T::S) -> T::R { 33 | n.usage(self, s) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/vimcat.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrcjkb/vimcats/60dfc68af5e30cf50475b0a2c64ee2bc8922a727/src/vimcat.rs -------------------------------------------------------------------------------- /src/vimdoc.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | use crate::{ 4 | lexer::{Name, Scope}, 5 | parser::{AliasKind, Divider, Module, Node}, 6 | Accept, FromLuaCATS, Layout, Settings, Visitor, 7 | }; 8 | 9 | /// Text Width 10 | const TW: usize = 80; 11 | 12 | #[derive(Debug)] 13 | pub struct VimDoc(String); 14 | 15 | impl Visitor for VimDoc { 16 | type R = String; 17 | type S = Settings; 18 | 19 | fn module(&self, n: &Module, s: &Self::S) -> Self::R { 20 | let mut doc = String::new(); 21 | let desc = n.desc.as_deref().unwrap_or_default(); 22 | doc.push_str(&self.divider(&Divider('='), s)); 23 | doc.push_str(desc); 24 | doc.push_str(&format!( 25 | "{:>w$}", 26 | format!("*{}*", n.name), 27 | w = TW - desc.len() 28 | )); 29 | doc.push('\n'); 30 | doc 31 | } 32 | 33 | fn divider(&self, n: &crate::parser::Divider, _: &Self::S) -> Self::R { 34 | let mut doc = String::with_capacity(TW - 1); 35 | for _ in 0..TW - 2 { 36 | doc.push(n.0); 37 | } 38 | doc.push('\n'); 39 | doc 40 | } 41 | 42 | fn brief(&self, n: &crate::parser::Brief, _: &Self::S) -> Self::R { 43 | let mut doc = n.desc.join("\n"); 44 | doc.push('\n'); 45 | doc 46 | } 47 | 48 | fn tag(&self, n: &crate::parser::Tag, _: &Self::S) -> Self::R { 49 | format!("{:>w$}", format!("*{}*", n.0), w = TW) 50 | } 51 | 52 | fn func(&self, n: &crate::parser::Func, s: &Self::S) -> Self::R { 53 | let mut doc = String::new(); 54 | let name_with_param = if !n.params.is_empty() { 55 | let args = n 56 | .params 57 | .iter() 58 | .map(|p| format!("{{{}}}", p.name)) 59 | .collect::>() 60 | .join(", "); 61 | format!( 62 | "{}{}({args})", 63 | n.prefix.left.as_deref().unwrap_or_default(), 64 | n.op 65 | ) 66 | } else { 67 | format!("{}{}()", n.prefix.left.as_deref().unwrap_or_default(), n.op) 68 | }; 69 | doc.push_str(&header( 70 | &name_with_param, 71 | &format!("{}{}", n.prefix.right.as_deref().unwrap_or_default(), n.op), 72 | )); 73 | if !n.desc.is_empty() { 74 | doc.push_str(&description(&n.desc.join("\n"), s.indent_width)) 75 | } 76 | doc.push('\n'); 77 | if !n.params.is_empty() { 78 | doc.push_str(&description("Parameters: ~", s.indent_width)); 79 | doc.push_str(&self.params(&n.params, s)); 80 | doc.push('\n'); 81 | } 82 | if !n.returns.is_empty() { 83 | doc.push_str(&description("Returns: ~", s.indent_width)); 84 | doc.push_str(&self.returns(&n.returns, s)); 85 | doc.push('\n'); 86 | } 87 | if !n.see.refs.is_empty() { 88 | doc.push_str(&self.see(&n.see, s)); 89 | } 90 | if let Some(usage) = &n.usage { 91 | doc.push_str(&self.usage(usage, s)); 92 | } 93 | doc 94 | } 95 | 96 | fn params(&self, n: &[crate::parser::Param], s: &Self::S) -> Self::R { 97 | let mut table = Table::new(s.indent_width); 98 | for param in n { 99 | let (name, ty) = match (s.expand_opt, ¶m.name) { 100 | (true, Name::Opt(n)) => (format!("{{{n}}}"), format!("(nil|{})", param.ty)), 101 | (_, n) => (format!("{{{n}}}"), format!("({})", param.ty)), 102 | }; 103 | match s.layout { 104 | Layout::Default => { 105 | table.add_row([name, ty, param.desc.join("\n")]); 106 | } 107 | Layout::Compact(n) => { 108 | table.add_row([ 109 | name, 110 | format!( 111 | "{ty} {}", 112 | param.desc.join(&format!("\n{}", " ".repeat(n as usize))) 113 | ), 114 | ]); 115 | } 116 | Layout::Mini(n) => { 117 | table.add_row([format!( 118 | "{name} {ty} {}", 119 | param.desc.join(&format!("\n{}", " ".repeat(n as usize))) 120 | )]); 121 | } 122 | } 123 | } 124 | table.to_string() 125 | } 126 | 127 | fn r#returns(&self, n: &[crate::parser::Return], s: &Self::S) -> Self::R { 128 | let mut table = Table::new(s.indent_width); 129 | for entry in n { 130 | if let Layout::Mini(n) = s.layout { 131 | table.add_row([format!( 132 | "({}) {}", 133 | entry.ty, 134 | if entry.desc.is_empty() { 135 | entry.name.clone().unwrap_or_default() 136 | } else { 137 | entry.desc.join(&format!("\n{}", " ".repeat(n as usize))) 138 | } 139 | )]); 140 | } else { 141 | table.add_row([ 142 | format!("({})", entry.ty), 143 | if entry.desc.is_empty() { 144 | entry.name.clone().unwrap_or_default() 145 | } else { 146 | entry.desc.join("\n") 147 | }, 148 | ]); 149 | } 150 | } 151 | table.to_string() 152 | } 153 | 154 | fn class(&self, n: &crate::parser::Class, s: &Self::S) -> Self::R { 155 | let mut doc = String::new(); 156 | let name = format!( 157 | "{}{}", 158 | n.name, 159 | n.parent 160 | .as_ref() 161 | .map_or(String::new(), |parent| format!(" : {parent}")) 162 | ); 163 | if let Some(prefix) = &n.prefix.right { 164 | doc.push_str(&header(&name, &format!("{prefix}.{}", n.name))); 165 | } else { 166 | doc.push_str(&header(&name, &n.name)); 167 | } 168 | if !n.desc.is_empty() { 169 | doc.push_str(&description(&n.desc.join("\n"), s.indent_width)); 170 | } 171 | doc.push('\n'); 172 | if !n.fields.is_empty() { 173 | doc.push_str(&description("Fields: ~", s.indent_width)); 174 | doc.push_str(&self.fields(&n.fields, s)); 175 | doc.push('\n'); 176 | } 177 | if !n.see.refs.is_empty() { 178 | doc.push_str(&self.see(&n.see, s)); 179 | } 180 | doc 181 | } 182 | 183 | fn fields(&self, n: &[crate::parser::Field], s: &Self::S) -> Self::R { 184 | let mut table = Table::new(s.indent_width); 185 | for field in n { 186 | let (name, ty) = match (s.expand_opt, &field.name) { 187 | (true, Name::Opt(n)) => (format!("{{{n}}}"), format!("(nil|{})", field.ty)), 188 | (_, n) => (format!("{{{n}}}"), format!("({})", field.ty)), 189 | }; 190 | if field.scope == Scope::Public { 191 | match s.layout { 192 | Layout::Default => { 193 | table.add_row([name, ty, field.desc.join("\n")]); 194 | } 195 | Layout::Compact(n) => { 196 | table.add_row([ 197 | name, 198 | format!( 199 | "{ty} {}", 200 | field.desc.join(&format!("\n{}", " ".repeat(n as usize))) 201 | ), 202 | ]); 203 | } 204 | Layout::Mini(n) => { 205 | table.add_row([format!( 206 | "{name} {ty} {}", 207 | field.desc.join(&format!("\n{}", " ".repeat(n as usize))) 208 | )]); 209 | } 210 | }; 211 | } 212 | } 213 | table.to_string() 214 | } 215 | 216 | fn r#enum(&self, n: &crate::parser::Enum, s: &Self::S) -> Self::R { 217 | let mut doc = String::new(); 218 | doc.push_str(&header(&n.name, &n.name)); 219 | if !n.desc.is_empty() { 220 | doc.push_str(&description(&n.desc.join("\n"), s.indent_width)); 221 | } 222 | doc.push('\n'); 223 | if !n.values.is_empty() { 224 | doc.push_str(&description("Values: ~", s.indent_width)); 225 | doc.push_str(&self.enum_values(&n.values, s)); 226 | doc.push('\n'); 227 | } 228 | doc 229 | } 230 | 231 | fn enum_values(&self, n: &[crate::parser::EnumValue], s: &Self::S) -> Self::R { 232 | let mut table = Table::new(s.indent_width); 233 | for value in n { 234 | table.add_row([value.name.to_string(), value.desc.join("\n")]); 235 | } 236 | table.to_string() 237 | } 238 | 239 | fn alias(&self, n: &crate::parser::Alias, s: &Self::S) -> Self::R { 240 | let mut doc = String::new(); 241 | if let Some(prefix) = &n.prefix.right { 242 | doc.push_str(&header(&n.name, &format!("{prefix}.{}", n.name))); 243 | } else { 244 | doc.push_str(&header(&n.name, &n.name)); 245 | } 246 | if !n.desc.is_empty() { 247 | doc.push_str(&description(&n.desc.join("\n"), s.indent_width)); 248 | } 249 | doc.push('\n'); 250 | match &n.kind { 251 | AliasKind::Type(ty) => { 252 | doc.push_str(&description("Type: ~", s.indent_width)); 253 | doc.push_str(&(" ").repeat(s.indent_width * 2)); 254 | doc.push_str(&ty.to_string()); 255 | doc.push('\n'); 256 | } 257 | AliasKind::Enum(variants) => { 258 | doc.push_str(&description("Variants: ~", s.indent_width)); 259 | let mut table = Table::new(s.indent_width); 260 | for (ty, desc) in variants { 261 | table.add_row([&format!("({})", ty), desc.as_deref().unwrap_or_default()]); 262 | } 263 | doc.push_str(&table.to_string()); 264 | } 265 | } 266 | doc.push('\n'); 267 | doc 268 | } 269 | 270 | fn r#type(&self, n: &crate::parser::Type, s: &Self::S) -> Self::R { 271 | let mut doc = String::new(); 272 | doc.push_str(&header( 273 | &format!("{}{}", n.prefix.left.as_deref().unwrap_or_default(), n.op), 274 | &format!("{}{}", n.prefix.right.as_deref().unwrap_or_default(), n.op), 275 | )); 276 | let (extract, desc) = &n.desc; 277 | if !extract.is_empty() { 278 | doc.push_str(&description(&extract.join("\n"), s.indent_width)); 279 | } 280 | doc.push('\n'); 281 | doc.push_str(&description("Type: ~", s.indent_width)); 282 | let mut table = Table::new(s.indent_width); 283 | table.add_row([&format!("({})", n.ty), desc.as_deref().unwrap_or_default()]); 284 | doc.push_str(&table.to_string()); 285 | doc.push('\n'); 286 | if !n.see.refs.is_empty() { 287 | doc.push_str(&self.see(&n.see, s)); 288 | } 289 | if let Some(usage) = &n.usage { 290 | doc.push_str(&self.usage(usage, s)); 291 | } 292 | doc 293 | } 294 | 295 | fn see(&self, n: &crate::parser::See, s: &Self::S) -> Self::R { 296 | let mut doc = String::new(); 297 | doc.push_str(&description("See: ~", s.indent_width)); 298 | for reff in &n.refs { 299 | doc.push_str(&(" ").repeat(s.indent_width * 2)); 300 | doc.push_str(&format!("|{reff}|\n")); 301 | } 302 | doc.push('\n'); 303 | doc 304 | } 305 | 306 | fn usage(&self, n: &crate::parser::Usage, s: &Self::S) -> Self::R { 307 | let mut doc = String::new(); 308 | doc.push_str(&description("Usage: ~", s.indent_width)); 309 | doc.push('>'); 310 | doc.push_str(n.lang.as_deref().unwrap_or("lua")); 311 | doc.push('\n'); 312 | doc.push_str(&textwrap::indent( 313 | &n.code, 314 | &(" ").repeat(s.indent_width * 2), 315 | )); 316 | doc.push_str("\n<\n\n"); 317 | doc 318 | } 319 | 320 | fn toc(&self, n: &str, nodes: &[Node], s: &Self::S) -> Self::R { 321 | let mut doc = String::new(); 322 | let module = self.module( 323 | &Module { 324 | name: n.to_string(), 325 | desc: Some("Table of Contents".into()), 326 | }, 327 | s, 328 | ); 329 | doc.push_str(&module); 330 | doc.push('\n'); 331 | for nod in nodes { 332 | if let Node::Module(x) = nod { 333 | let desc = x.desc.as_deref().unwrap_or_default(); 334 | doc.push_str(&format!( 335 | "{desc} {:·>w$}\n", 336 | format!(" |{}|", x.name), 337 | w = (TW - 1) - desc.len() 338 | )); 339 | } 340 | } 341 | doc 342 | } 343 | } 344 | 345 | impl FromLuaCATS for VimDoc { 346 | type Settings = Settings; 347 | fn from_emmy(t: &impl crate::Nodes, s: &Self::Settings) -> Self { 348 | let mut shelf = Self(String::new()); 349 | let nodes = t.nodes(); 350 | for node in nodes { 351 | if let Node::Toc(x) = node { 352 | shelf.0.push_str(&shelf.toc(x, nodes, s)); 353 | } else { 354 | shelf.0.push_str(&node.accept(&shelf, s)); 355 | } 356 | shelf.0.push('\n'); 357 | } 358 | shelf 359 | } 360 | } 361 | 362 | impl Display for VimDoc { 363 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 364 | f.write_str(self.0.as_str()) 365 | } 366 | } 367 | 368 | // ################# 369 | 370 | struct Table(comfy_table::Table, usize); 371 | 372 | impl Table { 373 | pub fn new(ident: usize) -> Self { 374 | let mut tbl = comfy_table::Table::new(); 375 | tbl.load_preset(comfy_table::presets::NOTHING); 376 | // tbl.column_iter_mut().map(|c| c.set_padding((0, 0))); 377 | Self(tbl, ident) 378 | } 379 | 380 | pub fn add_row>(&mut self, row: T) -> &Self { 381 | self.0.add_row(row); 382 | self 383 | } 384 | } 385 | 386 | impl std::fmt::Display for Table { 387 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 388 | f.write_str(&textwrap::indent( 389 | &self.0.trim_fmt(), 390 | &(" ").repeat((self.1 * 2) - 1), 391 | ))?; 392 | f.write_str("\n") 393 | } 394 | } 395 | 396 | #[inline] 397 | fn description(desc: &str, indent: usize) -> String { 398 | let mut d = textwrap::indent(desc, &(" ").repeat(indent)); 399 | d.push('\n'); 400 | d 401 | } 402 | 403 | #[inline] 404 | fn header(name: &str, tag: &str) -> String { 405 | let len = name.len(); 406 | let tag_str = format!("*{}*", tag); 407 | if len + tag_str.len() >= TW { 408 | return format!("{:>w$}\n{}\n", tag_str, name, w = TW); 409 | } 410 | format!("{}{:>w$}\n", name, tag_str, w = TW - len) 411 | } 412 | -------------------------------------------------------------------------------- /stylua.toml: -------------------------------------------------------------------------------- 1 | line_endings = "Unix" 2 | indent_type = "Spaces" 3 | indent_width = 4 4 | quote_style = "AutoPreferSingle" 5 | -------------------------------------------------------------------------------- /tests/basic.rs: -------------------------------------------------------------------------------- 1 | use vimcats::{vimdoc::VimDoc, FromLuaCATS, Settings, VimCats}; 2 | 3 | #[cfg(test)] 4 | macro_rules! vimcat { 5 | ($($src: expr),*) => {{ 6 | let mut vimcats = VimCats::default(); 7 | let s = Settings::default(); 8 | $( 9 | vimcats.for_help($src, &s).unwrap(); 10 | )* 11 | VimDoc::from_emmy(&vimcats, &s).to_string() 12 | }}; 13 | } 14 | 15 | #[test] 16 | fn multi_module() { 17 | let src = " 18 | ---@mod mod.intro Introduction 19 | ---@brief [[ 20 | --- 21 | ---We can have multiple `---@mod` tags so that we can have a block only for text. 22 | ---This is for the cases where you want bunch of block only just for text 23 | ---and does not contains any code. 24 | --- 25 | ---@brief ]] 26 | 27 | ---@mod mod.Human Human module 28 | 29 | local U = {} 30 | 31 | ---The Homosapien 32 | ---@class Human 33 | ---@field legs number Total number of legs 34 | ---@field hands number Total number of hands 35 | ---@field brain boolean Does humans have brain? 36 | 37 | ---Default traits of a human 38 | ---@type Human 39 | U.DEFAULT = { 40 | legs = 2, 41 | hands = 2, 42 | brain = false, 43 | } 44 | 45 | ---Creates a Human 46 | ---@return Human 47 | ---@usage [[ 48 | ---local H = require('Human') 49 | ---local human = H:create() 50 | --- 51 | ---print(getmetatable(human)) 52 | ---@usage ]] 53 | function U:create() 54 | return setmetatable(self.DEFAULT, { __index = self }) 55 | end 56 | 57 | return U 58 | "; 59 | 60 | let src2 = r#" 61 | ---@mod wo.desc 62 | 63 | local U = {} 64 | 65 | return U 66 | "#; 67 | 68 | assert_eq!( 69 | vimcat!(src, src2), 70 | "\ 71 | ============================================================================== 72 | Introduction *mod.intro* 73 | 74 | 75 | We can have multiple `---@mod` tags so that we can have a block only for text. 76 | This is for the cases where you want bunch of block only just for text 77 | and does not contains any code. 78 | 79 | 80 | ============================================================================== 81 | Human module *mod.Human* 82 | 83 | Human *Human* 84 | The Homosapien 85 | 86 | Fields: ~ 87 | {legs} (number) Total number of legs 88 | {hands} (number) Total number of hands 89 | {brain} (boolean) Does humans have brain? 90 | 91 | 92 | U.DEFAULT *U.DEFAULT* 93 | Default traits of a human 94 | 95 | Type: ~ 96 | (Human) 97 | 98 | 99 | U:create() *U:create* 100 | Creates a Human 101 | 102 | Returns: ~ 103 | (Human) 104 | 105 | Usage: ~ 106 | >lua 107 | local H = require('Human') 108 | local human = H:create() 109 | 110 | print(getmetatable(human)) 111 | < 112 | 113 | 114 | ============================================================================== 115 | *wo.desc* 116 | 117 | " 118 | ) 119 | } 120 | -------------------------------------------------------------------------------- /tests/golden.rs: -------------------------------------------------------------------------------- 1 | use goldenfile::Mint; 2 | use std::fs; 3 | use std::io::Write; 4 | use std::path::PathBuf; 5 | use vimcats::{vimdoc::VimDoc, FromLuaCATS, Settings, VimCats}; 6 | 7 | #[cfg(test)] 8 | macro_rules! vimcat { 9 | ($($src: expr),*) => {{ 10 | let mut vimcats = VimCats::default(); 11 | let s = Settings::default(); 12 | $( 13 | vimcats.for_help($src, &s).unwrap(); 14 | )* 15 | VimDoc::from_emmy(&vimcats, &s).to_string() 16 | }}; 17 | } 18 | 19 | fn run_golden(basename: String) { 20 | let mut mint = Mint::new("tests/golden"); 21 | let mut goldenfile = mint.new_goldenfile(format!("{}.txt", basename)).unwrap(); 22 | let content = 23 | fs::read_to_string(PathBuf::from(format!("tests/golden/{}.lua", basename))).unwrap(); 24 | writeln!(goldenfile, "{}", vimcat!(content.as_str())).unwrap(); 25 | } 26 | 27 | #[test] 28 | fn golden() { 29 | fs::read_dir("tests/golden") 30 | .unwrap() 31 | .filter_map(|entry| entry.ok()) // Filter out errors 32 | .filter_map(|entry| { 33 | let path = entry.path(); // Store PathBuf in a variable 34 | if path.extension().and_then(|ext| ext.to_str()) == Some("lua") { 35 | path.file_stem() 36 | .and_then(|stem| stem.to_str().map(|s| s.to_owned())) // Clone the basename as a String 37 | } else { 38 | None 39 | } 40 | }) 41 | .for_each(|basename| run_golden(basename)); 42 | } 43 | -------------------------------------------------------------------------------- /tests/golden/alias_and_type.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---@alias NoDesc string 4 | 5 | ---All the lines in the buffer 6 | ---@alias Lines string[] 7 | 8 | ---Vim operator-mode motions. 9 | --- 10 | ---Read `:h map-operator` 11 | ---@alias VMode 12 | ---| '"line"' # Vertical motion 13 | ---| '"char"' # Horizontal motion 14 | ---| 'v' 15 | ---| `some.ident` # Some identifier 16 | 17 | ---Returns all the content of the buffer 18 | ---@return Lines 19 | function U.get_all() 20 | return vim.api.nvim_buf_get_lines(0, 0, -1, false) 21 | end 22 | 23 | ---List of all the lines in the buffer 24 | ---It can be more than one 25 | ---@type Lines lines in a buffer 26 | ---@see Lines 27 | U.LINES = {} 28 | 29 | ---Global vim mode 30 | ---@type VMode 31 | ---@usage `print(require('plugin').VMODE)` 32 | U.VMODE = 'line' 33 | 34 | return U 35 | -------------------------------------------------------------------------------- /tests/golden/alias_and_type.txt: -------------------------------------------------------------------------------- 1 | NoDesc *NoDesc* 2 | 3 | Type: ~ 4 | string 5 | 6 | 7 | Lines *Lines* 8 | All the lines in the buffer 9 | 10 | Type: ~ 11 | string[] 12 | 13 | 14 | VMode *VMode* 15 | Vim operator-mode motions. 16 | 17 | Read `:h map-operator` 18 | 19 | Variants: ~ 20 | ("line") Vertical motion 21 | ("char") Horizontal motion 22 | ("v") 23 | (some.ident) Some identifier 24 | 25 | 26 | U.get_all() *U.get_all* 27 | Returns all the content of the buffer 28 | 29 | Returns: ~ 30 | (Lines) 31 | 32 | 33 | U.LINES *U.LINES* 34 | List of all the lines in the buffer 35 | It can be more than one 36 | 37 | Type: ~ 38 | (Lines) lines in a buffer 39 | 40 | See: ~ 41 | |Lines| 42 | 43 | 44 | U.VMODE *U.VMODE* 45 | Global vim mode 46 | 47 | Type: ~ 48 | (VMode) 49 | 50 | Usage: ~ 51 | >lua 52 | print(require('plugin').VMODE) 53 | < 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /tests/golden/brief.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---@brief [[ 4 | ---Any summary you wanted to write you can write here. 5 | ---There is no formatting here, 6 | ---the way you write in here, will be shown 7 | ---exactly in the help-doc 8 | --- 9 | ---An empty line can be used to denote a paragraph 10 | --- 11 | ---You can also write anything, like ordered list 12 | --- 1. first 13 | --- 2. second 14 | --- 3. third 15 | --- 16 | ---Some code blocks, but IDK whether it will be highlighted or not 17 | --- 18 | ---> 19 | --- for i = 1, 10, 1 do 20 | --- print(("%s Lua is awesome"):format(i)) 21 | --- end 22 | ---< 23 | --- 24 | ---NOTE: remember there is no formatting or text wrapping 25 | ---@brief ]] 26 | 27 | return U 28 | -------------------------------------------------------------------------------- /tests/golden/brief.txt: -------------------------------------------------------------------------------- 1 | Any summary you wanted to write you can write here. 2 | There is no formatting here, 3 | the way you write in here, will be shown 4 | exactly in the help-doc 5 | 6 | An empty line can be used to denote a paragraph 7 | 8 | You can also write anything, like ordered list 9 | 1. first 10 | 2. second 11 | 3. third 12 | 13 | Some code blocks, but IDK whether it will be highlighted or not 14 | 15 | > 16 | for i = 1, 10, 1 do 17 | print(("%s Lua is awesome"):format(i)) 18 | end 19 | < 20 | 21 | NOTE: remember there is no formatting or text wrapping 22 | 23 | 24 | -------------------------------------------------------------------------------- /tests/golden/classes.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---The Homosapien 4 | ---@class Human 5 | ---@field legs number Total number of legs 6 | ---@field hands number Total number of hands 7 | ---@field brain boolean Does humans have brain? 8 | 9 | ---@class SuperSecret 10 | ---@field first number First ingredient 11 | ---@field public second? number Second ingredient 12 | ---@field third number Third ingredient 13 | ---@field todo? number 14 | ---@field protected __secret_1 number Secret ingredient first 15 | ---@field private __secret_2? number 16 | 17 | ---Plugin's configuration 18 | ---@class CommentConfig 19 | ---@field padding boolean Add a space b/w comment and the line 20 | ---Whether the cursor should stay at its position 21 | ---NOTE: This only affects NORMAL mode mappings and doesn't work with dot-repeat 22 | --- 23 | ---@field sticky boolean 24 | ---Lines to be ignored while comment/uncomment. 25 | ---Could be a regex string or a function that returns a regex string. 26 | ---Example: Use '^$' to ignore empty lines 27 | --- 28 | ---@field ignore string|fun():string 29 | ---@field pre_hook fun(ctx:CommentCtx):string Function to be called before comment/uncomment 30 | ---@field post_hook fun(ctx:CommentCtx) Function to be called after comment/uncomment 31 | 32 | ---@class XMen : Homosapien 33 | ---@field power number Power quantifier 34 | ---@field [string] unknown Generic fields 35 | 36 | ---@class (exact) XactMen 37 | ---@field power number Power quantifier 38 | 39 | return U 40 | -------------------------------------------------------------------------------- /tests/golden/classes.txt: -------------------------------------------------------------------------------- 1 | Human *Human* 2 | The Homosapien 3 | 4 | Fields: ~ 5 | {legs} (number) Total number of legs 6 | {hands} (number) Total number of hands 7 | {brain} (boolean) Does humans have brain? 8 | 9 | 10 | SuperSecret *SuperSecret* 11 | 12 | Fields: ~ 13 | {first} (number) First ingredient 14 | {second?} (number) Second ingredient 15 | {third} (number) Third ingredient 16 | {todo?} (number) 17 | 18 | 19 | CommentConfig *CommentConfig* 20 | Plugin's configuration 21 | 22 | Fields: ~ 23 | {padding} (boolean) Add a space b/w comment and the line 24 | {sticky} (boolean) Whether the cursor should stay at its position 25 | NOTE: This only affects NORMAL mode mappings and doesn't work with dot-repeat 26 | 27 | {ignore} (string|fun():string) Lines to be ignored while comment/uncomment. 28 | Could be a regex string or a function that returns a regex string. 29 | Example: Use '^$' to ignore empty lines 30 | 31 | {pre_hook} (fun(ctx:CommentCtx):string) Function to be called before comment/uncomment 32 | {post_hook} (fun(ctx:CommentCtx)) Function to be called after comment/uncomment 33 | 34 | 35 | XMen : Homosapien *XMen* 36 | 37 | Fields: ~ 38 | {power} (number) Power quantifier 39 | {string} (unknown) Generic fields 40 | 41 | 42 | XactMen *XactMen* 43 | 44 | Fields: ~ 45 | {power} (number) Power quantifier 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /tests/golden/divider_and_tag.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---@divider = 4 | ---@tag kinda.module 5 | 6 | ---@divider - 7 | ---@tag kinda.section 8 | 9 | return U 10 | -------------------------------------------------------------------------------- /tests/golden/divider_and_tag.txt: -------------------------------------------------------------------------------- 1 | ============================================================================== 2 | 3 | *kinda.module* 4 | ------------------------------------------------------------------------------ 5 | 6 | *kinda.section* 7 | 8 | -------------------------------------------------------------------------------- /tests/golden/enum.lua: -------------------------------------------------------------------------------- 1 | ---Experimental features that can be enabled 2 | ---@enum rocks.ExperimentalFeature 3 | config.ExperimentalFeature = { 4 | --- Whether to install rocks stubs when using extensions 5 | --- like rocks-git.nvim or rocks-dev.nvim 6 | --- so that luarocks recognises them as dependencies 7 | ext_module_dependency_stubs = "ext_module_dependency_stubs", 8 | 9 | --- Some other experimental feature 10 | some_other_experimental_feature = "some_other_experimental_feature", 11 | } 12 | 13 | ---@enum RustAnalyzerCmd 14 | local RustAnalyzerCmd = { 15 | start = 'start', 16 | stop = 'stop', 17 | restart = 'restart', 18 | reload_settings = 'reloadSettings', 19 | } 20 | 21 | local U = {} 22 | 23 | return U 24 | -------------------------------------------------------------------------------- /tests/golden/enum.txt: -------------------------------------------------------------------------------- 1 | rocks.ExperimentalFeature *rocks.ExperimentalFeature* 2 | Experimental features that can be enabled 3 | 4 | Values: ~ 5 | ext_module_dependency_stubs Whether to install rocks stubs when using extensions 6 | like rocks-git.nvim or rocks-dev.nvim 7 | so that luarocks recognises them as dependencies 8 | some_other_experimental_feature Some other experimental feature 9 | 10 | 11 | RustAnalyzerCmd *RustAnalyzerCmd* 12 | 13 | Values: ~ 14 | start 15 | stop 16 | restart 17 | reload_settings 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /tests/golden/export.lua: -------------------------------------------------------------------------------- 1 | ---@mod module.config Configuration 2 | 3 | local Config = {} 4 | 5 | ---Get the config 6 | ---@return number 7 | function Config:get() 8 | return 3.14 9 | end 10 | 11 | ---@export Config 12 | return setmetatable(Config, { 13 | __index = function(this, k) 14 | return this.state[k] 15 | end, 16 | __newindex = function(this, k, v) 17 | this.state[k] = v 18 | end, 19 | }) 20 | -------------------------------------------------------------------------------- /tests/golden/export.txt: -------------------------------------------------------------------------------- 1 | ============================================================================== 2 | Configuration *module.config* 3 | 4 | Config:get() *Config:get* 5 | Get the config 6 | 7 | Returns: ~ 8 | (number) 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /tests/golden/functions.lua: -------------------------------------------------------------------------------- 1 | local U = { foo = {} } 2 | 3 | ---NOTE: Local functions are not part of the documentation 4 | ---Multiply two integer and print it 5 | ---@param this number First number 6 | ---@param that number Second number 7 | local function mul(this, that) 8 | print(this * that) 9 | end 10 | 11 | ---Add two integer and print it 12 | --- 13 | ---NOTE: This will be part of the public API 14 | ---@param this number First number 15 | ---@param that? number 16 | function U.sum(this, that) 17 | print(this + that or 0) 18 | end 19 | 20 | ---Subtract second from the first integer 21 | ---@param this number 22 | ---@param that number Second number 23 | ---@return number 24 | ---Some secret number that 25 | ---we don't know about 26 | ---@usage `require('module.U').sub(10, 5)` 27 | function U.sub(this, that) 28 | return this - that 29 | end 30 | 31 | ---This is a magical function 32 | ---@param this number Non-magical number #1 33 | ---@param that number Non-magical number #2 34 | ---@return number _ The magical number #1 35 | ---@return number #The magical number #2 36 | ---and the fun part is the description can span 37 | --- 38 | ---over mulitple lines and preserves empty lines 39 | ---@see U.mul 40 | ---@see U.sum 41 | ---@see U.sub 42 | U.magical = function(this, that) 43 | return (U.mul(this, that) / U.sum(that, this)), (U.sum(this, that) * U.sub(that, this)) 44 | end 45 | 46 | ---Function with variable arguments 47 | ---@param ... string[] 48 | function U.with_var_arg(...) end 49 | 50 | ---@param x integer 51 | ---@param ... unknown 52 | function U.with_var_arg_end(x, ...) end 53 | 54 | ---Class method deep access 55 | ---@return table 56 | function U.foo:bar() 57 | self.__index = self 58 | return setmetatable({}, self) 59 | end 60 | 61 | ---Method deep access 62 | ---@return table 63 | function U.foo.baz() 64 | return U.foo:bar() 65 | end 66 | 67 | ---Method with long name and signature just below tag spillover length 68 | function U.very_long_function_name____________() end 69 | ---Method with long name and signature just above tag spillover length 70 | function U.very_long_function_name_____________() end 71 | ---Method with long param and signature just below tag spillover length 72 | ---@param long_param_name______________ string 73 | function U.short_function_name1(long_param_name______________) end 74 | ---Method with long param and signature just above tag spillover length 75 | ---@param long_param_name_______________ string 76 | function U.short_function_name2(long_param_name_______________) end 77 | 78 | return U 79 | -------------------------------------------------------------------------------- /tests/golden/functions.txt: -------------------------------------------------------------------------------- 1 | U.sum({this}, {that?}) *U.sum* 2 | Add two integer and print it 3 | 4 | NOTE: This will be part of the public API 5 | 6 | Parameters: ~ 7 | {this} (number) First number 8 | {that?} (number) 9 | 10 | 11 | U.sub({this}, {that}) *U.sub* 12 | Subtract second from the first integer 13 | 14 | Parameters: ~ 15 | {this} (number) 16 | {that} (number) Second number 17 | 18 | Returns: ~ 19 | (number) Some secret number that 20 | we don't know about 21 | 22 | Usage: ~ 23 | >lua 24 | require('module.U').sub(10, 5) 25 | < 26 | 27 | 28 | U.magical({this}, {that}) *U.magical* 29 | This is a magical function 30 | 31 | Parameters: ~ 32 | {this} (number) Non-magical number #1 33 | {that} (number) Non-magical number #2 34 | 35 | Returns: ~ 36 | (number) The magical number #1 37 | (number) The magical number #2 38 | and the fun part is the description can span 39 | 40 | over mulitple lines and preserves empty lines 41 | 42 | See: ~ 43 | |U.mul| 44 | |U.sum| 45 | |U.sub| 46 | 47 | 48 | U.with_var_arg({...}) *U.with_var_arg* 49 | Function with variable arguments 50 | 51 | Parameters: ~ 52 | {...} (string[]) 53 | 54 | 55 | U.with_var_arg_end({x}, {...}) *U.with_var_arg_end* 56 | 57 | Parameters: ~ 58 | {x} (integer) 59 | {...} (unknown) 60 | 61 | 62 | U.foo:bar() *U.foo:bar* 63 | Class method deep access 64 | 65 | Returns: ~ 66 | (table) 67 | 68 | 69 | U.foo.baz() *U.foo.baz* 70 | Method deep access 71 | 72 | Returns: ~ 73 | (table) 74 | 75 | 76 | U.very_long_function_name____________() *U.very_long_function_name____________* 77 | Method with long name and signature just below tag spillover length 78 | 79 | 80 | *U.very_long_function_name_____________* 81 | U.very_long_function_name_____________() 82 | Method with long name and signature just above tag spillover length 83 | 84 | 85 | U.short_function_name1({long_param_name______________}) *U.short_function_name1* 86 | Method with long param and signature just below tag spillover length 87 | 88 | Parameters: ~ 89 | {long_param_name______________} (string) 90 | 91 | 92 | *U.short_function_name2* 93 | U.short_function_name2({long_param_name_______________}) 94 | Method with long param and signature just above tag spillover length 95 | 96 | Parameters: ~ 97 | {long_param_name_______________} (string) 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /tests/golden/module.lua: -------------------------------------------------------------------------------- 1 | ---@mod mod.intro Introduction 2 | ---@brief [[ 3 | --- 4 | ---We can have multiple `---@mod` tags so that we can have a block only for text. 5 | ---This is for the cases where you want bunch of block only just for text 6 | ---and does not contains any code. 7 | --- 8 | ---@brief ]] 9 | 10 | ---@mod mod.Human Human module 11 | 12 | local U = {} 13 | 14 | ---The Homosapien 15 | ---@class Human 16 | ---@field legs number Total number of legs 17 | ---@field hands number Total number of hands 18 | ---@field brain boolean Does humans have brain? 19 | 20 | ---Default traits of a human 21 | ---@type Human 22 | U.DEFAULT = { 23 | legs = 2, 24 | hands = 2, 25 | brain = false, 26 | } 27 | 28 | ---Creates a Human 29 | ---@return Human 30 | ---@usage [[ 31 | ---local H = require('Human') 32 | ---local human = H:create() 33 | --- 34 | ---print(getmetatable(human)) 35 | ---@usage ]] 36 | function U:create() 37 | return setmetatable(self.DEFAULT, { __index = self }) 38 | end 39 | 40 | return U 41 | -------------------------------------------------------------------------------- /tests/golden/module.txt: -------------------------------------------------------------------------------- 1 | ============================================================================== 2 | Introduction *mod.intro* 3 | 4 | 5 | We can have multiple `---@mod` tags so that we can have a block only for text. 6 | This is for the cases where you want bunch of block only just for text 7 | and does not contains any code. 8 | 9 | 10 | ============================================================================== 11 | Human module *mod.Human* 12 | 13 | Human *Human* 14 | The Homosapien 15 | 16 | Fields: ~ 17 | {legs} (number) Total number of legs 18 | {hands} (number) Total number of hands 19 | {brain} (boolean) Does humans have brain? 20 | 21 | 22 | U.DEFAULT *U.DEFAULT* 23 | Default traits of a human 24 | 25 | Type: ~ 26 | (Human) 27 | 28 | 29 | U:create() *U:create* 30 | Creates a Human 31 | 32 | Returns: ~ 33 | (Human) 34 | 35 | Usage: ~ 36 | >lua 37 | local H = require('Human') 38 | local human = H:create() 39 | 40 | print(getmetatable(human)) 41 | < 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /tests/golden/multi_extension.lua: -------------------------------------------------------------------------------- 1 | ---@class lz.n.PluginSpec: lz.n.PluginBase,lz.n.PluginSpecHandlers,lz.n.PluginHooks 2 | --- 3 | --- The plugin name (not its main module), e.g. "sweetie.nvim" 4 | ---@field [1] string 5 | 6 | local U = {} 7 | return U 8 | -------------------------------------------------------------------------------- /tests/golden/multi_extension.txt: -------------------------------------------------------------------------------- 1 | *lz.n.PluginSpec* 2 | lz.n.PluginSpec : lz.n.PluginBase, lz.n.PluginSpecHandlers, lz.n.PluginHooks 3 | 4 | Fields: ~ 5 | {1} (string) 6 | The plugin name (not its main module), e.g. "sweetie.nvim" 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /tests/golden/multiline_param.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---Trigger a rebuild of one or more projects. 4 | ---@param opts table|nil optional configuration options: 5 | --- * {select_mode} (JdtProjectSelectMode) Show prompt 6 | --- to select projects or select all. Defaults 7 | --- to 'prompt' 8 | --- 9 | --- * {full_build} (boolean) full rebuild or 10 | --- incremental build. Defaults to true (full build) 11 | ---@param reserverd table|nil reserved for the future use 12 | ---@return boolean 13 | function U.multi_line(opts, reserverd) 14 | print(vim.inspect(opts), vim.inspect(reserverd)) 15 | 16 | return true 17 | end 18 | 19 | ---Multiline but missing description 20 | ---@param n number 21 | ---This is a special 22 | --- 23 | ---number 24 | ---@param m number 25 | ---And this is also 26 | --- 27 | ---@return number 28 | function U.missing_desc(n, m) 29 | return n + m 30 | end 31 | 32 | return U 33 | -------------------------------------------------------------------------------- /tests/golden/multiline_param.txt: -------------------------------------------------------------------------------- 1 | U.multi_line({opts}, {reserverd}) *U.multi_line* 2 | Trigger a rebuild of one or more projects. 3 | 4 | Parameters: ~ 5 | {opts} (table|nil) optional configuration options: 6 | * {select_mode} (JdtProjectSelectMode) Show prompt 7 | to select projects or select all. Defaults 8 | to 'prompt' 9 | 10 | * {full_build} (boolean) full rebuild or 11 | incremental build. Defaults to true (full build) 12 | {reserverd} (table|nil) reserved for the future use 13 | 14 | Returns: ~ 15 | (boolean) 16 | 17 | 18 | U.missing_desc({n}, {m}) *U.missing_desc* 19 | Multiline but missing description 20 | 21 | Parameters: ~ 22 | {n} (number) This is a special 23 | 24 | number 25 | {m} (number) And this is also 26 | 27 | 28 | Returns: ~ 29 | (number) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /tests/golden/namespaced_classes.lua: -------------------------------------------------------------------------------- 1 | ---@class lz.n.KeysBase: vim.keymap.set.Opts 2 | ---@field desc? string 3 | ---@field noremap? boolean 4 | ---@field remap? boolean 5 | ---@field expr? boolean 6 | ---@field nowait? boolean 7 | ---@field ft? string|string[] 8 | 9 | ---@class lz.n.KeysSpec: lz.n.KeysBase 10 | ---@field [1] string lhs 11 | ---@field [2]? string|fun()|false rhs 12 | ---@field mode? string|string[] 13 | 14 | local U = {} 15 | return U 16 | -------------------------------------------------------------------------------- /tests/golden/namespaced_classes.txt: -------------------------------------------------------------------------------- 1 | lz.n.KeysBase : vim.keymap.set.Opts *lz.n.KeysBase* 2 | 3 | Fields: ~ 4 | {desc?} (string) 5 | {noremap?} (boolean) 6 | {remap?} (boolean) 7 | {expr?} (boolean) 8 | {nowait?} (boolean) 9 | {ft?} (string|string[]) 10 | 11 | 12 | lz.n.KeysSpec : lz.n.KeysBase *lz.n.KeysSpec* 13 | 14 | Fields: ~ 15 | {1} (string) lhs 16 | {2?} (string|fun()|false) rhs 17 | {mode?} (string|string[]) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /tests/golden/private.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---@private 4 | ---This is a private function which is exported 5 | ---But not considered as part of the API 6 | function U.private() 7 | print('I am private!') 8 | end 9 | 10 | ---Only this will be documented 11 | function U.ok() 12 | print('Ok! I am exported') 13 | end 14 | 15 | ---@protected 16 | function U.no_emmy() 17 | print('Protected func with no emmylua!') 18 | end 19 | 20 | return U 21 | -------------------------------------------------------------------------------- /tests/golden/private.txt: -------------------------------------------------------------------------------- 1 | U.ok() *U.ok* 2 | Only this will be documented 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /tests/golden/toc.lua: -------------------------------------------------------------------------------- 1 | ---@toc my-plugin.contents 2 | 3 | ---@mod first.module First Module 4 | 5 | ---@mod second.module Second Module 6 | 7 | ---@mod third.module Third Module 8 | 9 | local U = {} 10 | 11 | return U 12 | -------------------------------------------------------------------------------- /tests/golden/toc.txt: -------------------------------------------------------------------------------- 1 | ============================================================================== 2 | Table of Contents *my-plugin.contents* 3 | 4 | First Module ···················································· |first.module| 5 | Second Module ·················································· |second.module| 6 | Third Module ···················································· |third.module| 7 | 8 | ============================================================================== 9 | First Module *first.module* 10 | 11 | ============================================================================== 12 | Second Module *second.module* 13 | 14 | ============================================================================== 15 | Third Module *third.module* 16 | 17 | 18 | -------------------------------------------------------------------------------- /tests/golden/usage.lua: -------------------------------------------------------------------------------- 1 | local U = {} 2 | 3 | ---Prints a message 4 | ---@param msg string Message 5 | ---@usage lua [[ 6 | ---require('module.U').sum(10, 5) 7 | ---@usage ]] 8 | function U.echo(msg) 9 | print(msg) 10 | end 11 | 12 | ---Add a number to 10 13 | ---@param this number A number 14 | ---@usage `require('module.U').sum(5)` 15 | function U.sum(this) 16 | print(10 + this) 17 | end 18 | 19 | return U 20 | -------------------------------------------------------------------------------- /tests/golden/usage.txt: -------------------------------------------------------------------------------- 1 | U.echo({msg}) *U.echo* 2 | Prints a message 3 | 4 | Parameters: ~ 5 | {msg} (string) Message 6 | 7 | Usage: ~ 8 | >lua 9 | require('module.U').sum(10, 5) 10 | < 11 | 12 | 13 | U.sum({this}) *U.sum* 14 | Add a number to 10 15 | 16 | Parameters: ~ 17 | {this} (number) A number 18 | 19 | Usage: ~ 20 | >lua 21 | require('module.U').sum(5) 22 | < 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /tests/types.rs: -------------------------------------------------------------------------------- 1 | use chumsky::Parser; 2 | use vimcats::lexer::{Lexer, Member, Name, Ty}; 3 | 4 | macro_rules! b { 5 | ($t:expr) => { 6 | Box::new($t) 7 | }; 8 | } 9 | 10 | #[test] 11 | fn types() { 12 | let type_parse = Lexer::init(); 13 | 14 | macro_rules! check { 15 | ($s:expr, $ty:expr) => { 16 | assert_eq!( 17 | type_parse 18 | .parse(concat!("---@type ", $s)) 19 | .unwrap() 20 | .into_iter() 21 | .next() 22 | .unwrap() 23 | .0, 24 | vimcats::lexer::TagType::Type($ty, None) 25 | ); 26 | }; 27 | } 28 | 29 | check!("nil", Ty::Nil); 30 | check!("any", Ty::Any); 31 | check!("unknown", Ty::Unknown); 32 | check!("boolean", Ty::Boolean); 33 | check!("string", Ty::String); 34 | check!("number", Ty::Number); 35 | check!("integer", Ty::Integer); 36 | check!("function", Ty::Function); 37 | check!("thread", Ty::Thread); 38 | check!("userdata", Ty::Userdata); 39 | check!("lightuserdata", Ty::Lightuserdata); 40 | check!("Any-Thing.El_se", Ty::Ref("Any-Thing.El_se".into())); 41 | 42 | check!( 43 | "(string|number|table)[]", 44 | Ty::Array(b!(Ty::Union( 45 | b!(Ty::String), 46 | b!(Ty::Union( 47 | b!(Ty::Number), 48 | b!(Ty::Table(Some(( 49 | b!(Ty::String), 50 | b!(Ty::Array(b!(Ty::String))) 51 | )))) 52 | )) 53 | ))) 54 | ); 55 | 56 | check!( 57 | "table[]", 58 | Ty::Array(b!(Ty::Table(Some(( 59 | b!(Ty::String), 60 | b!(Ty::Dict(vec![ 61 | (Name::Req("get".into()), Ty::String), 62 | (Name::Req("set".into()), Ty::String), 63 | ])) 64 | ))))) 65 | ); 66 | 67 | check!( 68 | "table", 69 | Ty::Table(Some(( 70 | b!(Ty::String), 71 | b!(Ty::Fun( 72 | vec![(Name::Req("a".into()), Ty::String)], 73 | Some(vec![Ty::String]) 74 | )) 75 | ))) 76 | ); 77 | 78 | check!( 79 | "table>", 80 | Ty::Table(Some(( 81 | b!(Ty::Fun(vec![], None)), 82 | b!(Ty::Table(Some((b!(Ty::String), b!(Ty::Number))))) 83 | ))) 84 | ); 85 | 86 | check!( 87 | "table[]", 88 | Ty::Array(b!(Ty::Table(Some(( 89 | b!(Ty::String), 90 | b!(Ty::Union( 91 | b!(Ty::String), 92 | b!(Ty::Union(b!(Ty::Array(b!(Ty::String))), b!(Ty::Boolean))) 93 | )) 94 | ))))) 95 | ); 96 | 97 | check!( 98 | "fun( 99 | a: string, b: string|number|boolean, c: number[][], d?: SomeClass 100 | ): number, string|string[]", 101 | Ty::Fun( 102 | vec![ 103 | (Name::Req("a".into()), Ty::String), 104 | ( 105 | Name::Req("b".into()), 106 | Ty::Union( 107 | b!(Ty::String), 108 | b!(Ty::Union(b!(Ty::Number), b!(Ty::Boolean))) 109 | ) 110 | ), 111 | ( 112 | Name::Req("c".into()), 113 | Ty::Array(b!(Ty::Array(b!(Ty::Number)))) 114 | ), 115 | (Name::Opt("d".into()), Ty::Ref("SomeClass".into())), 116 | ], 117 | Some(vec![ 118 | Ty::Number, 119 | Ty::Union(b!(Ty::String), b!(Ty::Array(b!(Ty::String)))) 120 | ]) 121 | ) 122 | ); 123 | 124 | // "fun(a: string, b: (string|table)[]|boolean, c: string[], d: number[][]): string|string[]", 125 | 126 | check!( 127 | "fun( 128 | a: string, 129 | b?: string, 130 | c: function, 131 | d: fun(z: string), 132 | e: string|string[]|table|fun(y: string[]|{ get: function }|string): string 133 | ): table", 134 | Ty::Fun( 135 | vec![ 136 | (Name::Req("a".into()), Ty::String), 137 | (Name::Opt("b".into()), Ty::String), 138 | (Name::Req("c".into()), Ty::Function), 139 | (Name::Req( 140 | "d".into()), 141 | Ty::Fun(vec![ 142 | (Name::Req("z".into()), Ty::String) 143 | ], None) 144 | ), 145 | (Name::Req( 146 | "e".into()), 147 | Ty::Union( 148 | b!(Ty::String), 149 | b!(Ty::Union( 150 | b!(Ty::Array(b!(Ty::String))), 151 | b!(Ty::Union( 152 | b!(Ty::Table(Some((b!(Ty::String), b!(Ty::String))))), 153 | b!(Ty::Fun( 154 | vec![(Name::Req( 155 | "y".into()), 156 | Ty::Union( 157 | b!(Ty::Array(b!(Ty::String))), 158 | b!(Ty::Union( 159 | b!(Ty::Dict(vec![ 160 | (Name::Req("get".into()), Ty::Function) 161 | ])), 162 | b!(Ty::String) 163 | )) 164 | ) 165 | ),], 166 | Some(vec![Ty::String]) 167 | )) 168 | )) 169 | )) 170 | ) 171 | ) 172 | ], 173 | Some(vec![Ty::Table(Some((b!(Ty::String), b!(Ty::String))))]) 174 | ) 175 | ); 176 | 177 | check!( 178 | "{ 179 | inner: string, 180 | get: fun(a: unknown), 181 | set: fun(a: unknown), 182 | __proto__?: { _?: unknown } 183 | }", 184 | Ty::Dict(vec![ 185 | (Name::Req("inner".into()), Ty::String), 186 | ( 187 | Name::Req("get".into()), 188 | Ty::Fun(vec![(Name::Req("a".into()), Ty::Unknown)], None,) 189 | ), 190 | ( 191 | Name::Req("set".into()), 192 | Ty::Fun(vec![(Name::Req("a".into()), Ty::Unknown)], None) 193 | ), 194 | ( 195 | Name::Opt("__proto__".into()), 196 | Ty::Dict(vec![(Name::Opt("_".into()), Ty::Unknown)]) 197 | ) 198 | ]) 199 | ); 200 | 201 | check!( 202 | r#"'"g@"'|string[]|'"g@$"'|number"#, 203 | Ty::Union( 204 | b!(Ty::Member(Member::Literal(r#""g@""#.into()))), 205 | b!(Ty::Union( 206 | b!(Ty::Array(b!(Ty::String))), 207 | b!(Ty::Union( 208 | b!(Ty::Member(Member::Literal(r#""g@$""#.into()))), 209 | b!(Ty::Number) 210 | )) 211 | )) 212 | ) 213 | ); 214 | 215 | check!( 216 | "any|any|string|(string|number)[]|fun(a: string)|table|userdata[]", 217 | Ty::Union( 218 | b!(Ty::Any), 219 | b!(Ty::Union( 220 | b!(Ty::Any), 221 | b!(Ty::Union( 222 | b!(Ty::String), 223 | b!(Ty::Union( 224 | b!(Ty::Array(b!(Ty::Union(b!(Ty::String), b!(Ty::Number))))), 225 | b!(Ty::Union( 226 | b!(Ty::Fun(vec![(Name::Req("a".into()), Ty::String)], None)), 227 | b!(Ty::Union( 228 | b!(Ty::Table(Some((b!(Ty::String), b!(Ty::Number))))), 229 | b!(Ty::Array(b!(Ty::Userdata))) 230 | )) 231 | )) 232 | )) 233 | )) 234 | )) 235 | ) 236 | ); 237 | } 238 | -------------------------------------------------------------------------------- /tests/with_settings.rs: -------------------------------------------------------------------------------- 1 | use vimcats::{vimdoc::VimDoc, FromLuaCATS, Settings, VimCats}; 2 | 3 | const CODE: &str = r#" 4 | local U = {} 5 | 6 | ---@alias ID string 7 | 8 | ---@class User 9 | ---@field name string 10 | ---@field email string 11 | ---@field id ID 12 | 13 | ---A Pi 14 | ---@type number 15 | U.Pi = 3.14 16 | 17 | ---Creates a PI 18 | ---@return number 19 | ---@usage `require('Pi'):create()` 20 | function U:create() 21 | return self.Pi 22 | end 23 | 24 | return U 25 | "#; 26 | 27 | #[test] 28 | fn rename_with_return() { 29 | let mut vimcats = VimCats::new(); 30 | let s = Settings { 31 | prefix_func: true, 32 | prefix_alias: true, 33 | prefix_class: true, 34 | prefix_type: true, 35 | ..Default::default() 36 | }; 37 | 38 | vimcats.for_help(CODE, &s).unwrap(); 39 | 40 | assert_eq!( 41 | VimDoc::from_emmy(&vimcats, &s).to_string(), 42 | "\ 43 | ID *U.ID* 44 | 45 | Type: ~ 46 | string 47 | 48 | 49 | User *U.User* 50 | 51 | Fields: ~ 52 | {name} (string) 53 | {email} (string) 54 | {id} (ID) 55 | 56 | 57 | U.Pi *U.Pi* 58 | A Pi 59 | 60 | Type: ~ 61 | (number) 62 | 63 | 64 | U:create() *U:create* 65 | Creates a PI 66 | 67 | Returns: ~ 68 | (number) 69 | 70 | Usage: ~ 71 | >lua 72 | require('Pi'):create() 73 | < 74 | 75 | 76 | " 77 | ); 78 | } 79 | 80 | #[test] 81 | fn rename_with_mod() { 82 | let src = format!("---@mod awesome This is working {CODE}"); 83 | 84 | let mut vimcats = VimCats::new(); 85 | let s = Settings { 86 | prefix_func: true, 87 | prefix_alias: true, 88 | prefix_class: true, 89 | prefix_type: true, 90 | ..Default::default() 91 | }; 92 | 93 | vimcats.for_help(&src, &s).unwrap(); 94 | 95 | assert_eq!( 96 | VimDoc::from_emmy(&vimcats, &s).to_string(), 97 | "\ 98 | ============================================================================== 99 | This is working *awesome* 100 | 101 | ID *awesome.ID* 102 | 103 | Type: ~ 104 | string 105 | 106 | 107 | User *awesome.User* 108 | 109 | Fields: ~ 110 | {name} (string) 111 | {email} (string) 112 | {id} (ID) 113 | 114 | 115 | U.Pi *awesome.Pi* 116 | A Pi 117 | 118 | Type: ~ 119 | (number) 120 | 121 | 122 | U:create() *awesome:create* 123 | Creates a PI 124 | 125 | Returns: ~ 126 | (number) 127 | 128 | Usage: ~ 129 | >lua 130 | require('Pi'):create() 131 | < 132 | 133 | 134 | " 135 | ); 136 | } 137 | 138 | #[test] 139 | fn expand_opt() { 140 | let src = " 141 | local M = {} 142 | 143 | ---@class HelloWorld 144 | ---@field message? string First message to the world 145 | ---@field private opts? table 146 | ---@field secret table Sauce 147 | 148 | ---Prints given value 149 | ---@param message string 150 | ---@param opts? table 151 | function M.echo(message, opts) 152 | return print(message) 153 | end 154 | 155 | return M 156 | "; 157 | 158 | let mut vimcats = VimCats::new(); 159 | let s = Settings { 160 | expand_opt: true, 161 | ..Default::default() 162 | }; 163 | 164 | vimcats.for_help(src, &s).unwrap(); 165 | 166 | assert_eq!( 167 | VimDoc::from_emmy(&vimcats, &s).to_string(), 168 | "\ 169 | HelloWorld *HelloWorld* 170 | 171 | Fields: ~ 172 | {message} (nil|string) First message to the world 173 | {secret} (table) Sauce 174 | 175 | 176 | M.echo({message}, {opts?}) *M.echo* 177 | Prints given value 178 | 179 | Parameters: ~ 180 | {message} (string) 181 | {opts} (nil|table) 182 | 183 | 184 | " 185 | ); 186 | } 187 | --------------------------------------------------------------------------------