├── .editorconfig ├── .eslintignore ├── .gitattributes ├── .github └── workflows │ └── deploy-extension.yml ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .vscode ├── launch.json └── tasks.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── packages ├── language-server │ ├── LICENSE │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── common.ts │ │ ├── completions │ │ │ ├── completion-provider.ts │ │ │ ├── filters.ts │ │ │ ├── for-loop.ts │ │ │ ├── functions.ts │ │ │ ├── global-variables.ts │ │ │ ├── local-variables.ts │ │ │ └── template-paths.ts │ │ ├── configuration │ │ │ ├── configuration-manager.ts │ │ │ └── language-server-settings.ts │ │ ├── constants │ │ │ └── template-usage.ts │ │ ├── definitions │ │ │ └── definition-provider.ts │ │ ├── document-cache.ts │ │ ├── hovers │ │ │ ├── filters.ts │ │ │ ├── for-loop.ts │ │ │ ├── functions.ts │ │ │ ├── global-variables.ts │ │ │ ├── hover-provider.ts │ │ │ └── local-variables.ts │ │ ├── index.ts │ │ ├── semantic-tokens │ │ │ ├── semantic-tokens-provider.ts │ │ │ └── tokens-provider.ts │ │ ├── server.ts │ │ ├── signature-helps │ │ │ └── signature-help-provider.ts │ │ └── utils │ │ │ ├── bottom-top-cursor-iterator.ts │ │ │ ├── compare-positions.ts │ │ │ ├── docker │ │ │ ├── command.ts │ │ │ └── config.ts │ │ │ ├── document-uri-to-fs-path.ts │ │ │ ├── exec.ts │ │ │ ├── files │ │ │ └── fileStat.ts │ │ │ ├── find-element-by-position.ts │ │ │ ├── find-parent-by-type.ts │ │ │ ├── fs-path-to-document-uri.ts │ │ │ ├── is-empty-embedded.ts │ │ │ ├── node │ │ │ ├── getStringNodeValue.ts │ │ │ └── index.ts │ │ │ ├── parse-twig.ts │ │ │ ├── point-to-position.ts │ │ │ ├── positions-to-range.ts │ │ │ ├── pre-order-cursor-iterator.ts │ │ │ ├── range-contains-position.ts │ │ │ ├── read-dir.ts │ │ │ ├── symfony │ │ │ └── twigConfig.ts │ │ │ ├── to-previous-sibling-or-parent-iterator.ts │ │ │ ├── trim-twig-extension.ts │ │ │ └── validate-twig-document.ts │ ├── tsconfig.json │ └── tsconfig.tsbuildinfo └── vscode │ ├── .vscodeignore │ ├── LICENSE │ ├── README.md │ ├── assets │ └── logo.png │ ├── languages │ └── twig.configuration.json │ ├── package.json │ ├── src │ └── extension.ts │ ├── syntaxes │ └── html.tmLanguage.json │ ├── tsconfig.json │ └── tsconfig.tsbuildinfo └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | end_of_line = lf 9 | charset = utf-8 10 | trim_trailing_whitespace = true 11 | insert_final_newline = true 12 | indent_style = space 13 | indent_size = 2 14 | 15 | [*.{diff,md}] 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | out/ 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.wasm binary 2 | -------------------------------------------------------------------------------- /.github/workflows/deploy-extension.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Extension 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: actions/setup-node@v1 13 | with: 14 | node-version: 20 15 | - run: npm install --workspaces=false --prefix packages/vscode 16 | - name: Publish to Visual Studio Marketplace 17 | uses: HaaLeo/publish-vscode-extension@v1 18 | with: 19 | pat: ${{ secrets.VS_MARKETPLACE_TOKEN }} 20 | packagePath: ./packages/vscode 21 | registryUrl: https://marketplace.visualstudio.com 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | out/ 3 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | out/ 3 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Extension", 6 | "type": "extensionHost", 7 | "request": "launch", 8 | "preLaunchTask": "${defaultBuildTask}", 9 | "args": [ 10 | "--extensionDevelopmentPath=${workspaceFolder}/packages/vscode", 11 | "--disable-extensions", 12 | ], 13 | "outFiles": [ 14 | "${workspaceFolder}/packages/vscode/out/*.js" 15 | ], 16 | }, 17 | { 18 | "name": "Server", 19 | "type": "node", 20 | "request": "attach", 21 | "port": 6009, 22 | "restart": true, 23 | "sourceMaps": true, 24 | "smartStep": true, 25 | "outFiles": [ 26 | "${workspaceRoot}/packages/language-server/out/**/*.js" 27 | ] 28 | } 29 | ], 30 | "compounds": [ 31 | { 32 | "name": "Extension + Server", 33 | "configurations": [ 34 | "Extension", 35 | "Server" 36 | ], 37 | "stopAll": true 38 | } 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // See https://go.microsoft.com/fwlink/?LinkId=733558 2 | // for the documentation about the tasks.json format 3 | { 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "watch", 9 | "problemMatcher": "$tsc-watch", 10 | "isBackground": true, 11 | "presentation": { 12 | "reveal": "never" 13 | }, 14 | "group": { 15 | "kind": "build", 16 | "isDefault": true 17 | } 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ## v0.7.0 (2024-12-06) 8 | 9 | ## v0.6.0 (2024-12-05) 10 | 11 | ## v0.5.1 (2023-10-21) 12 | 13 | ## v0.5.0 (2023-09-30) 14 | 15 | #### :rocket: Enhancement 16 | * `language-server` 17 | * [#26](https://github.com/kaermorchen/twig-language-server/pull/26) Add completion support for empty embedded. ([@moetelo](https://github.com/moetelo)) 18 | * [#29](https://github.com/kaermorchen/twig-language-server/pull/29) Treat property function call as function call in semantic tokenization. ([@moetelo](https://github.com/moetelo)) 19 | * `language-server`, `vscode` 20 | * [#28](https://github.com/kaermorchen/twig-language-server/pull/28) Add `ConfigurationManager` for VS Code configuration. ([@moetelo](https://github.com/moetelo)) 21 | * `vscode` 22 | * [#22](https://github.com/kaermorchen/twig-language-server/pull/22) Remove unused imports. ([@moetelo](https://github.com/moetelo)) 23 | * Other 24 | * [#24](https://github.com/kaermorchen/twig-language-server/pull/24) Add `--disable-extensions` arg for VS Code in debug. ([@moetelo](https://github.com/moetelo)) 25 | 26 | #### Committers: 1 27 | - Mikhail ([@moetelo](https://github.com/moetelo)) 28 | 29 | ## v0.4.0 (2023-09-11) 30 | 31 | #### :rocket: Enhancement 32 | * `vscode` 33 | * [#20](https://github.com/kaermorchen/twig-language-server/pull/20) Simplify, refine tmLanguage.json ([@IHIutch](https://github.com/IHIutch)) 34 | 35 | #### Committers: 1 36 | - Jonathan Hutchison ([@IHIutch](https://github.com/IHIutch)) 37 | 38 | ## v0.3.0 (2023-08-25) 39 | 40 | ## v0.2.3 (2023-08-16) 41 | 42 | #### :bug: Bug Fix 43 | * `vscode` 44 | * [#17](https://github.com/kaermorchen/twig-language-server/pull/17) Fix extension build ([@kaermorchen](https://github.com/kaermorchen)) 45 | 46 | #### Committers: 1 47 | - Stanislav Romanov ([@kaermorchen](https://github.com/kaermorchen)) 48 | 49 | ## v0.2.2 (2023-07-31) 50 | 51 | #### :memo: Documentation 52 | * `vscode` 53 | * [#15](https://github.com/kaermorchen/twig-language-server/pull/15) Update README.md ([@kaermorchen](https://github.com/kaermorchen)) 54 | 55 | #### Committers: 1 56 | - Stanislav Romanov ([@kaermorchen](https://github.com/kaermorchen)) 57 | 58 | ## v0.2.1 (2023-07-31) 59 | 60 | ## v0.2.0 (2023-07-31) 61 | 62 | #### :rocket: Enhancement 63 | * `language-server`, `vscode` 64 | * [#13](https://github.com/kaermorchen/twig-language-server/pull/13) Added deploy the extension on publish event ([@kaermorchen](https://github.com/kaermorchen)) 65 | * `vscode` 66 | * [#12](https://github.com/kaermorchen/twig-language-server/pull/12) Add language-server as dependency ([@kaermorchen](https://github.com/kaermorchen)) 67 | 68 | #### Committers: 1 69 | - Stanislav Romanov ([@kaermorchen](https://github.com/kaermorchen)) 70 | 71 | ## v0.1.0 (2023-07-30) 72 | 73 | #### :rocket: Enhancement 74 | * Other 75 | * [#11](https://github.com/kaermorchen/twig-language-server/pull/11) Added release-it ([@kaermorchen](https://github.com/kaermorchen)) 76 | * `language-server`, `vscode` 77 | * [#10](https://github.com/kaermorchen/twig-language-server/pull/10) Added readme, license and package settings ([@kaermorchen](https://github.com/kaermorchen)) 78 | * [#7](https://github.com/kaermorchen/twig-language-server/pull/7) Semantic highlight ([@kaermorchen](https://github.com/kaermorchen)) 79 | * [#2](https://github.com/kaermorchen/twig-language-server/pull/2) Convert to NPM packages ([@kaermorchen](https://github.com/kaermorchen)) 80 | * `language-server` 81 | * [#9](https://github.com/kaermorchen/twig-language-server/pull/9) Added `for` `loop` hover ([@kaermorchen](https://github.com/kaermorchen)) 82 | * [#8](https://github.com/kaermorchen/twig-language-server/pull/8) Add completions for `for` loop ([@kaermorchen](https://github.com/kaermorchen)) 83 | * [#6](https://github.com/kaermorchen/twig-language-server/pull/6) Signature helps ([@kaermorchen](https://github.com/kaermorchen)) 84 | * [#5](https://github.com/kaermorchen/twig-language-server/pull/5) Add local variables completion ([@kaermorchen](https://github.com/kaermorchen)) 85 | * [#4](https://github.com/kaermorchen/twig-language-server/pull/4) Template name completions ([@kaermorchen](https://github.com/kaermorchen)) 86 | 87 | #### :memo: Documentation 88 | * `language-server`, `vscode` 89 | * [#10](https://github.com/kaermorchen/twig-language-server/pull/10) Added readme, license and package settings ([@kaermorchen](https://github.com/kaermorchen)) 90 | 91 | #### Committers: 1 92 | - Stanislav Romanov ([@kaermorchen](https://github.com/kaermorchen)) 93 | 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Twig Language Server 2 | 3 | This monorepo contains a couple things: 4 | 5 | 1. [Twig Language Server](packages/language-server/) 6 | 1. [VSCode Twig extension](packages/vscode/) 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.7.0", 3 | "repository": "https://github.com/kaermorchen/twig-language-server", 4 | "private": true, 5 | "workspaces": [ 6 | "packages/language-server", 7 | "packages/vscode" 8 | ], 9 | "scripts": { 10 | "build": "tsc --build", 11 | "watch": "npm run build -- --watch", 12 | "release": "release-it" 13 | }, 14 | "author": "Stanislav Romanov ", 15 | "license": "Mozilla Public License 2.0", 16 | "release-it": { 17 | "hooks": { 18 | "after:bump": "npm run build" 19 | }, 20 | "plugins": { 21 | "@release-it-plugins/lerna-changelog": { 22 | "infile": "CHANGELOG.md", 23 | "launchEditor": false 24 | }, 25 | "@release-it-plugins/workspaces": { 26 | "workspaces": [ 27 | "packages/language-server" 28 | ], 29 | "additionalManifests": { 30 | "versionUpdates": [ 31 | "packages/language-server/package.json", 32 | "packages/vscode/package.json" 33 | ], 34 | "dependencyUpdates": [ 35 | "packages/language-server/package.json", 36 | "packages/vscode/package.json" 37 | ] 38 | } 39 | } 40 | }, 41 | "git": { 42 | "tagName": "v${version}" 43 | }, 44 | "github": { 45 | "release": true, 46 | "tokenRef": "GITHUB_AUTH" 47 | }, 48 | "npm": { 49 | "publish": false 50 | } 51 | }, 52 | "devDependencies": { 53 | "@release-it-plugins/lerna-changelog": "^6.0.0", 54 | "@release-it-plugins/workspaces": "^4.0.0", 55 | "release-it": "^16.1.3" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /packages/language-server/LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /packages/language-server/README.md: -------------------------------------------------------------------------------- 1 | # Twig Language Server 2 | 3 | TypeScript-powered language server for [Twig](https://twig.symfony.com) templates. 4 | 5 | ## Note 6 | It uses [tree-sitter-twig](https://github.com/kaermorchen/tree-sitter-twig) under the hood. 7 | -------------------------------------------------------------------------------- /packages/language-server/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twig-language-server", 3 | "version": "0.0.0", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "twig-language-server", 9 | "version": "0.0.0", 10 | "dependencies": { 11 | "vscode-languageserver": "^8.1.0", 12 | "vscode-languageserver-textdocument": "^1.0.8" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "^20.2.6", 16 | "@types/vscode": "^1.79.0", 17 | "typescript": "^5.1.3" 18 | } 19 | }, 20 | "node_modules/@types/node": { 21 | "version": "20.2.6", 22 | "resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.6.tgz", 23 | "integrity": "sha512-GQBWUtGoefMEOx/vu+emHEHU5aw6JdDoEtZhoBrHFPZbA/YNRFfN996XbBASEWdvmLSLyv9FKYppYGyZjCaq/g==", 24 | "dev": true 25 | }, 26 | "node_modules/@types/vscode": { 27 | "version": "1.79.0", 28 | "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.79.0.tgz", 29 | "integrity": "sha512-Tfowu2rSW8hVGbqzQLSPlOEiIOYYryTkgJ+chMecpYiJcnw9n0essvSiclnK+Qh/TcSVJHgaK4EMrQDZjZJ/Sw==", 30 | "dev": true 31 | }, 32 | "node_modules/typescript": { 33 | "version": "5.1.3", 34 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.3.tgz", 35 | "integrity": "sha512-XH627E9vkeqhlZFQuL+UsyAXEnibT0kWR2FWONlr4sTjvxyJYnyefgrkyECLzM5NenmKzRAy2rR/OlYLA1HkZw==", 36 | "dev": true, 37 | "bin": { 38 | "tsc": "bin/tsc", 39 | "tsserver": "bin/tsserver" 40 | }, 41 | "engines": { 42 | "node": ">=14.17" 43 | } 44 | }, 45 | "node_modules/vscode-jsonrpc": { 46 | "version": "8.1.0", 47 | "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.1.0.tgz", 48 | "integrity": "sha512-6TDy/abTQk+zDGYazgbIPc+4JoXdwC8NHU9Pbn4UJP1fehUyZmM4RHp5IthX7A6L5KS30PRui+j+tbbMMMafdw==", 49 | "engines": { 50 | "node": ">=14.0.0" 51 | } 52 | }, 53 | "node_modules/vscode-languageserver": { 54 | "version": "8.1.0", 55 | "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-8.1.0.tgz", 56 | "integrity": "sha512-eUt8f1z2N2IEUDBsKaNapkz7jl5QpskN2Y0G01T/ItMxBxw1fJwvtySGB9QMecatne8jFIWJGWI61dWjyTLQsw==", 57 | "dependencies": { 58 | "vscode-languageserver-protocol": "3.17.3" 59 | }, 60 | "bin": { 61 | "installServerIntoExtension": "bin/installServerIntoExtension" 62 | } 63 | }, 64 | "node_modules/vscode-languageserver-protocol": { 65 | "version": "3.17.3", 66 | "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.3.tgz", 67 | "integrity": "sha512-924/h0AqsMtA5yK22GgMtCYiMdCOtWTSGgUOkgEDX+wk2b0x4sAfLiO4NxBxqbiVtz7K7/1/RgVrVI0NClZwqA==", 68 | "dependencies": { 69 | "vscode-jsonrpc": "8.1.0", 70 | "vscode-languageserver-types": "3.17.3" 71 | } 72 | }, 73 | "node_modules/vscode-languageserver-textdocument": { 74 | "version": "1.0.8", 75 | "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.8.tgz", 76 | "integrity": "sha512-1bonkGqQs5/fxGT5UchTgjGVnfysL0O8v1AYMBjqTbWQTFn721zaPGDYFkOKtfDgFiSgXM3KwaG3FMGfW4Ed9Q==" 77 | }, 78 | "node_modules/vscode-languageserver-types": { 79 | "version": "3.17.3", 80 | "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.3.tgz", 81 | "integrity": "sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==" 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /packages/language-server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twig-language-server", 3 | "version": "0.7.0", 4 | "author": "Stanislav Romanov ", 5 | "license": "Mozilla Public License 2.0", 6 | "main": "out/index.js", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/kaermorchen/twig-language-server", 10 | "directory": "packages/language-server" 11 | }, 12 | "files": [ 13 | "out/", 14 | "LICENSE", 15 | "README.md" 16 | ], 17 | "scripts": {}, 18 | "devDependencies": { 19 | "@types/node": "^20.2.6", 20 | "typescript": "^5.1.3" 21 | }, 22 | "dependencies": { 23 | "tree-sitter-twig": "^0.7.0", 24 | "vscode-languageserver": "^8.1.0", 25 | "vscode-languageserver-textdocument": "^1.0.8", 26 | "vscode-uri": "^3.0.7", 27 | "web-tree-sitter": "^0.20.8" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /packages/language-server/src/common.ts: -------------------------------------------------------------------------------- 1 | import { 2 | MarkupKind, 3 | SignatureInformation, 4 | ParameterInformation, 5 | MarkupContent, 6 | CompletionItemKind, 7 | CompletionItem, 8 | } from 'vscode-languageserver'; 9 | 10 | export const twigGlobalVariables = [ 11 | { 12 | label: `_self`, 13 | documentation: 'References the current template name', 14 | }, 15 | { 16 | label: `_context`, 17 | documentation: 'References the current context', 18 | }, 19 | { 20 | label: `_charset`, 21 | documentation: 'References the current charset', 22 | }, 23 | ]; 24 | 25 | export const twigTests = [ 26 | { 27 | label: 'constant', 28 | documentation: { 29 | kind: MarkupKind.Markdown, 30 | value: [ 31 | '`constant` checks if a variable has the exact same value as a constant. You can use either global constants or class constants:', 32 | '```twig', 33 | "{% if post.status is constant('Post::PUBLISHED') %}", 34 | ' the status attribute is exactly the same as Post::PUBLISHED', 35 | '{% endif %}', 36 | '```', 37 | 'You can test constants from object instances as well:', 38 | '```twig', 39 | "{% if post.status is constant('PUBLISHED', post) %}", 40 | ' the status attribute is exactly the same as Post::PUBLISHED', 41 | '{% endif %}', 42 | '```', 43 | ].join('\n'), 44 | }, 45 | parameters: [ 46 | { 47 | label: 'string ...$values', 48 | }, 49 | ], 50 | return: 'mixed', 51 | }, 52 | { 53 | label: 'divisible by', 54 | documentation: { 55 | kind: MarkupKind.Markdown, 56 | value: [ 57 | '`divisible by` checks if a variable is divisible by a number', 58 | ].join('\n'), 59 | }, 60 | }, 61 | { 62 | label: 'same as', 63 | documentation: { 64 | kind: MarkupKind.Markdown, 65 | value: [ 66 | '`same as` checks if a variable is the same as another variable. This is equivalent to === in PHP', 67 | ].join('\n'), 68 | }, 69 | }, 70 | { 71 | label: `defined`, 72 | documentation: 73 | '`defined` checks if a variable is defined in the current context', 74 | }, 75 | { 76 | label: `empty`, 77 | documentation: 78 | '`empty` checks if a variable is an empty string, an empty array, an empty hash, exactly false, or exactly null.', 79 | }, 80 | { 81 | label: `even`, 82 | documentation: '`even` returns true if the given number is even', 83 | }, 84 | { 85 | label: `iterable`, 86 | documentation: 87 | '`iterable` checks if a variable is an array or a traversable object', 88 | }, 89 | { 90 | label: `null`, 91 | documentation: '`null` returns true if the variable is null:', 92 | }, 93 | { 94 | label: `odd`, 95 | documentation: '`odd` returns true if the given number is odd', 96 | }, 97 | { 98 | label: `rootform`, 99 | documentation: 100 | 'This test will check if the current form does not have a parent form view.', 101 | }, 102 | { 103 | label: `selectedchoice`, 104 | documentation: 105 | 'This test will check if the current choice is equal to the selected_value or if the current choice is in the array (when selected_value is an array).', 106 | }, 107 | ]; 108 | 109 | type twigFunction = { 110 | label: string; 111 | documentation?: MarkupContent; 112 | parameters?: ParameterInformation[]; 113 | return?: string; 114 | }; 115 | 116 | export const twigFunctions: twigFunction[] = [ 117 | { 118 | label: 'max', 119 | documentation: { 120 | kind: MarkupKind.Markdown, 121 | value: [ 122 | 'Returns the biggest value of a sequence or a set of values:', 123 | '```twig', 124 | '{{ max(1, 3, 2) }}', 125 | '{{ max([1, 3, 2]) }}', 126 | '```', 127 | 'When called with a mapping, max ignores keys and only compares values:', 128 | '```twig', 129 | '{{ max({2: "e", 1: "a", 3: "b", 5: "d", 4: "c"}) }}', 130 | '{# returns "e" #}', 131 | '```', 132 | ].join('\n'), 133 | }, 134 | parameters: [ 135 | { 136 | label: 'mixed ...$values', 137 | documentation: 'Any comparable values.', 138 | }, 139 | ], 140 | return: 'mixed', 141 | }, 142 | { 143 | label: 'min', 144 | documentation: { 145 | kind: MarkupKind.Markdown, 146 | value: [ 147 | 'Returns the lowest value of a sequence or a set of values', 148 | '```twig', 149 | '{{ min(1, 3, 2) }}', 150 | '{{ min([1, 3, 2]) }}', 151 | '```', 152 | 'When called with a mapping, min ignores keys and only compares values:', 153 | '```twig', 154 | '{{ min({2: "e", 3: "a", 1: "b", 5: "d", 4: "c"}) }}', 155 | '{# returns "a" #}', 156 | '```', 157 | ].join('\n'), 158 | }, 159 | parameters: [ 160 | { 161 | label: 'mixed ...$values', 162 | documentation: 'Any comparable values.', 163 | }, 164 | ], 165 | return: 'mixed', 166 | }, 167 | { 168 | label: 'range', 169 | documentation: { 170 | kind: MarkupKind.Markdown, 171 | value: [ 172 | 'Returns a list containing an arithmetic progression of integers:', 173 | '```twig', 174 | '{% for i in range(0, 3) %}', 175 | ' {{ i }},', 176 | '{% endfor %}', 177 | '```', 178 | ].join('\n'), 179 | }, 180 | parameters: [ 181 | { 182 | label: 'int $low', 183 | documentation: 'The first value of the sequence.', 184 | }, 185 | { 186 | label: 'int $high', 187 | documentation: 'The highest possible value of the sequence.', 188 | }, 189 | { 190 | label: 'int $step = 1', 191 | documentation: 'The increment between elements of the sequence.', 192 | }, 193 | ], 194 | return: 'array', 195 | }, 196 | { 197 | label: 'constant', 198 | documentation: { 199 | kind: MarkupKind.Markdown, 200 | value: [ 201 | 'Provides the ability to get constants from instances as well as class/global constants.', 202 | ].join('\n'), 203 | }, 204 | parameters: [ 205 | { 206 | label: 'string $constant', 207 | documentation: 'The name of the constant', 208 | }, 209 | { 210 | label: 'object|null $object = null', 211 | documentation: 'The object to get the constant from', 212 | }, 213 | ], 214 | return: 'string', 215 | }, 216 | { 217 | label: 'cycle', 218 | documentation: { 219 | kind: MarkupKind.Markdown, 220 | value: ['Cycles over a value.'].join('\n'), 221 | }, 222 | parameters: [ 223 | { 224 | label: '\\ArrayAccess|array $values', 225 | }, 226 | { 227 | label: 'int $position', 228 | documentation: 'The object to get the constant from', 229 | }, 230 | ], 231 | return: 'string', 232 | }, 233 | { 234 | label: 'random', 235 | documentation: { 236 | kind: MarkupKind.Markdown, 237 | value: [ 238 | 'Returns a random value depending on the supplied parameter type:', 239 | '- a random item from a \\Traversable or array', 240 | '- a random character from a string', 241 | '- a random integer between 0 and the integer parameter.', 242 | ].join('\n'), 243 | }, 244 | parameters: [ 245 | { 246 | label: '\\Traversable|array|int|float|string $values = null', 247 | documentation: 'The values to pick a random item from', 248 | }, 249 | { 250 | label: 'int|null $max = null', 251 | documentation: 'Maximum value used when $values is an int', 252 | }, 253 | ], 254 | return: 'mixed', 255 | }, 256 | { 257 | label: 'date', 258 | documentation: { 259 | kind: MarkupKind.Markdown, 260 | value: [ 261 | 'Converts an input to a DateTime instance.', 262 | '```twig', 263 | "{% if date(user.created_at) < date('+2days') %}", 264 | ' {# do something #}', 265 | '{% endif %}', 266 | '```', 267 | ].join('\n'), 268 | }, 269 | parameters: [ 270 | { 271 | label: '\\DateTimeInterface|string|null $date = null', 272 | documentation: 'A date or null to use the current time', 273 | }, 274 | { 275 | label: '\\DateTimeZone|string|false|null $timezone = null', 276 | documentation: 277 | 'The target timezone, null to use the default, false to leave unchanged', 278 | }, 279 | ], 280 | return: '\\DateTimeInterface', 281 | }, 282 | { 283 | label: 'dump', 284 | documentation: { 285 | kind: MarkupKind.Markdown, 286 | value: [ 287 | 'The dump function dumps information about a template variable. This is mostly useful to debug a template that does not behave as expected by introspecting its variables:', 288 | '```twig', 289 | '{{ dump(user) }}', 290 | '```', 291 | ].join('\n'), 292 | }, 293 | parameters: [ 294 | { 295 | label: 'mixed $context', 296 | documentation: 'The context to dump', 297 | }, 298 | ], 299 | }, 300 | { 301 | label: 'include', 302 | documentation: { 303 | kind: MarkupKind.Markdown, 304 | value: ['Renders a template.'].join('\n'), 305 | }, 306 | parameters: [ 307 | { 308 | label: 'array $context', 309 | }, 310 | { 311 | label: 'string|array $template', 312 | documentation: 313 | 'The template to render or an array of templates to try consecutively', 314 | }, 315 | { 316 | label: 'array $variables', 317 | documentation: 'The variables to pass to the template', 318 | }, 319 | { 320 | label: 'bool $withContext', 321 | }, 322 | { 323 | label: 'bool $ignoreMissing', 324 | documentation: 'Whether to ignore missing templates or not', 325 | }, 326 | { 327 | label: 'bool $sandboxed', 328 | documentation: 'Whether to sandbox the template or not', 329 | }, 330 | ], 331 | return: 'string', 332 | }, 333 | { 334 | label: 'source', 335 | documentation: { 336 | kind: MarkupKind.Markdown, 337 | value: ['Returns a template content without rendering it.'].join('\n'), 338 | }, 339 | parameters: [ 340 | { 341 | label: 'string $name', 342 | documentation: 'The template name', 343 | }, 344 | { 345 | label: 'bool $ignoreMissing', 346 | documentation: 'Whether to ignore missing templates or not', 347 | }, 348 | ], 349 | return: 'string', 350 | }, 351 | { 352 | label: 'attribute', 353 | documentation: { 354 | kind: MarkupKind.Markdown, 355 | value: ['Returns the attribute value for a given array/object.'].join( 356 | '\n' 357 | ), 358 | }, 359 | parameters: [ 360 | { 361 | label: 'mixed $object', 362 | documentation: 'The object or array from where to get the item', 363 | }, 364 | { 365 | label: 'mixed $item', 366 | documentation: 'The item to get from the array or object', 367 | }, 368 | { 369 | label: 'array $arguments', 370 | documentation: 371 | 'An array of arguments to pass if the item is an object method', 372 | }, 373 | ], 374 | return: 'mixed', 375 | }, 376 | { 377 | label: 'block', 378 | documentation: { 379 | kind: MarkupKind.Markdown, 380 | value: [ 381 | 'When a template uses inheritance and if you want to print a block multiple times, use the `block` function', 382 | ].join('\n'), 383 | }, 384 | parameters: [ 385 | { 386 | label: 'string $name', 387 | }, 388 | { 389 | label: 'string $template', 390 | }, 391 | ], 392 | }, 393 | { 394 | label: 'html_classes', 395 | documentation: { 396 | kind: MarkupKind.Markdown, 397 | value: [ 398 | 'The `html_classes` function returns a string by conditionally joining class names together', 399 | ].join('\n'), 400 | }, 401 | parameters: [ 402 | { 403 | label: 'mixed ...$args', 404 | }, 405 | ], 406 | return: 'string', 407 | }, 408 | { 409 | label: 'parent', 410 | documentation: { 411 | kind: MarkupKind.Markdown, 412 | value: [ 413 | "When a template uses inheritance, it's possible to render the contents of the parent block when overriding a block by using the `parent` function", 414 | ].join('\n'), 415 | }, 416 | }, 417 | { 418 | label: 'country_timezones', 419 | documentation: { 420 | kind: MarkupKind.Markdown, 421 | value: [ 422 | 'The `country_timezones` function returns the names of the timezones associated with a given country code', 423 | ].join('\n'), 424 | }, 425 | parameters: [ 426 | { 427 | label: 'string $country', 428 | }, 429 | ], 430 | return: 'array', 431 | }, 432 | { 433 | label: 'language_names', 434 | documentation: { 435 | kind: MarkupKind.Markdown, 436 | value: [ 437 | 'The `language_names` function returns the names of the languages', 438 | ].join('\n'), 439 | }, 440 | parameters: [ 441 | { 442 | label: 'string $locale = null', 443 | }, 444 | ], 445 | return: 'array', 446 | }, 447 | { 448 | label: 'script_names', 449 | documentation: { 450 | kind: MarkupKind.Markdown, 451 | value: [ 452 | 'The `script_names` function returns the names of the scripts', 453 | ].join('\n'), 454 | }, 455 | parameters: [ 456 | { 457 | label: 'string $locale = null', 458 | }, 459 | ], 460 | return: 'array', 461 | }, 462 | { 463 | label: 'country_names', 464 | documentation: { 465 | kind: MarkupKind.Markdown, 466 | value: [ 467 | 'The `country_names` function returns the names of the countries', 468 | ].join('\n'), 469 | }, 470 | parameters: [ 471 | { 472 | label: 'string $locale = null', 473 | }, 474 | ], 475 | return: 'array', 476 | }, 477 | { 478 | label: 'locale_names', 479 | documentation: { 480 | kind: MarkupKind.Markdown, 481 | value: [ 482 | 'The `locale_names` function returns the names of the locales', 483 | ].join('\n'), 484 | }, 485 | parameters: [ 486 | { 487 | label: 'string $locale = null', 488 | }, 489 | ], 490 | return: 'array', 491 | }, 492 | { 493 | label: 'currency_names', 494 | documentation: { 495 | kind: MarkupKind.Markdown, 496 | value: [ 497 | 'The `currency_names` function returns the names of the currencies', 498 | ].join('\n'), 499 | }, 500 | parameters: [ 501 | { 502 | label: 'string $locale = null', 503 | }, 504 | ], 505 | return: 'array', 506 | }, 507 | { 508 | label: 'timezone_names', 509 | documentation: { 510 | kind: MarkupKind.Markdown, 511 | value: [ 512 | 'The `timezone_names` function returns the names of the timezones', 513 | ].join('\n'), 514 | }, 515 | parameters: [ 516 | { 517 | label: 'string $locale = null', 518 | }, 519 | ], 520 | return: 'array', 521 | }, 522 | { 523 | label: 'template_from_string', 524 | documentation: { 525 | kind: MarkupKind.Markdown, 526 | value: [ 527 | 'Loads a template from a string.', 528 | '```twig', 529 | '{{ include(template_from_string("Hello {{ name }}")) }}', 530 | '```', 531 | ].join('\n'), 532 | }, 533 | parameters: [ 534 | { 535 | label: 'string $template', 536 | documentation: 537 | 'A template as a string or object implementing __toString()', 538 | }, 539 | { 540 | label: 'string $name = null', 541 | documentation: 542 | 'An optional name of the template to be used in error messages', 543 | }, 544 | ], 545 | }, 546 | { 547 | label: 'render', 548 | parameters: [ 549 | { 550 | label: 'string|ControllerReference $uri', 551 | }, 552 | { 553 | label: 'array options = []', 554 | }, 555 | ], 556 | }, 557 | { 558 | label: 'render_esi', 559 | parameters: [ 560 | { 561 | label: 'string|ControllerReference $uri', 562 | }, 563 | { 564 | label: 'array options = []', 565 | }, 566 | ], 567 | }, 568 | { 569 | label: 'fragment_uri', 570 | parameters: [ 571 | { 572 | label: 'ControllerReference controller', 573 | }, 574 | { 575 | label: 'boolean absolute = false', 576 | }, 577 | { 578 | label: 'boolean strict = true', 579 | }, 580 | { 581 | label: 'boolean sign = true', 582 | }, 583 | ], 584 | }, 585 | { 586 | label: 'controller', 587 | parameters: [ 588 | { 589 | label: 'string controller', 590 | }, 591 | { 592 | label: 'array attributes = []', 593 | }, 594 | { 595 | label: 'array query = []', 596 | }, 597 | ], 598 | }, 599 | { 600 | label: 'asset', 601 | parameters: [ 602 | { 603 | label: 'string path', 604 | }, 605 | { 606 | label: 'string|null packageName = null', 607 | }, 608 | ], 609 | }, 610 | { 611 | label: 'asset_version', 612 | parameters: [ 613 | { 614 | label: 'string|null packageName = null', 615 | }, 616 | ], 617 | }, 618 | { 619 | label: 'csrf_token', 620 | parameters: [ 621 | { 622 | label: 'string intention', 623 | }, 624 | ], 625 | }, 626 | { 627 | label: 'is_granted', 628 | parameters: [ 629 | { 630 | label: 'string role', 631 | }, 632 | { 633 | label: 'object object = null', 634 | }, 635 | { 636 | label: 'string field = null', 637 | }, 638 | ], 639 | }, 640 | { 641 | label: 'logout_path', 642 | parameters: [ 643 | { 644 | label: 'string key = null', 645 | }, 646 | ], 647 | }, 648 | { 649 | label: 'logout_url', 650 | parameters: [ 651 | { 652 | label: 'string key = null', 653 | }, 654 | ], 655 | }, 656 | { 657 | label: 'path', 658 | parameters: [ 659 | { 660 | label: 'string route_name', 661 | }, 662 | { 663 | label: 'array route_parameters = []', 664 | }, 665 | { 666 | label: 'boolean relative = false', 667 | }, 668 | ], 669 | }, 670 | { 671 | label: 'url', 672 | parameters: [ 673 | { 674 | label: 'string route_name', 675 | }, 676 | { 677 | label: 'array route_parameters = []', 678 | }, 679 | { 680 | label: 'boolean schemeRelative = false', 681 | }, 682 | ], 683 | }, 684 | { 685 | label: 'absolute_url', 686 | parameters: [ 687 | { 688 | label: 'string path', 689 | }, 690 | ], 691 | }, 692 | { 693 | label: 'relative_path', 694 | parameters: [ 695 | { 696 | label: 'string path', 697 | }, 698 | ], 699 | }, 700 | { 701 | label: 'impersonation_exit_path', 702 | parameters: [ 703 | { 704 | label: 'string exitTo = null', 705 | }, 706 | ], 707 | }, 708 | { 709 | label: 'impersonation_exit_url', 710 | parameters: [ 711 | { 712 | label: 'string exitTo = null', 713 | }, 714 | ], 715 | }, 716 | { 717 | label: 't', 718 | parameters: [ 719 | { 720 | label: 'string message', 721 | }, 722 | { 723 | label: 'array parameters = []', 724 | }, 725 | { 726 | label: "string domain = 'messages'", 727 | }, 728 | ], 729 | }, 730 | { 731 | label: 'form', 732 | }, 733 | { 734 | label: 'form_end', 735 | }, 736 | { 737 | label: 'form_errors', 738 | }, 739 | { 740 | label: 'form_help', 741 | }, 742 | { 743 | label: 'form_label', 744 | }, 745 | { 746 | label: 'form_parent', 747 | }, 748 | { 749 | label: 'form_rest', 750 | }, 751 | { 752 | label: 'form_row', 753 | }, 754 | { 755 | label: 'form_start', 756 | }, 757 | { 758 | label: 'form_widget', 759 | }, 760 | { 761 | label: 'importmap', 762 | }, 763 | ]; 764 | 765 | export const twigFilters: twigFunction[] = [ 766 | { 767 | label: 'date', 768 | documentation: { 769 | kind: MarkupKind.Markdown, 770 | value: [ 771 | 'Converts a date to the given format.', 772 | '```twig', 773 | '{{ post.published_at|date("m/d/Y") }}', 774 | '```', 775 | ].join('\n'), 776 | }, 777 | parameters: [ 778 | { 779 | label: 'string|null $format = null', 780 | documentation: 'The date format', 781 | }, 782 | { 783 | label: '\\DateTimeZone|string|false|null $timezone = null', 784 | documentation: 'The date timezone', 785 | }, 786 | ], 787 | return: 'string', 788 | }, 789 | { 790 | label: 'date_modify', 791 | documentation: { 792 | kind: MarkupKind.Markdown, 793 | value: [ 794 | 'Returns a new date object modified.', 795 | '```twig', 796 | '{{ post.published_at|date_modify("-1day")|date("m/d/Y") }}', 797 | '```', 798 | ].join('\n'), 799 | }, 800 | parameters: [ 801 | { 802 | label: 'string $modifier', 803 | documentation: 'A modifier string', 804 | }, 805 | ], 806 | }, 807 | { 808 | label: 'format', 809 | documentation: { 810 | kind: MarkupKind.Markdown, 811 | value: ['Returns a formatted string.'].join('\n'), 812 | }, 813 | parameters: [ 814 | { 815 | label: '...$values', 816 | }, 817 | ], 818 | return: 'string', 819 | }, 820 | { 821 | label: 'replace', 822 | documentation: { 823 | kind: MarkupKind.Markdown, 824 | value: ['Replaces strings within a string.'].join('\n'), 825 | }, 826 | parameters: [ 827 | { 828 | label: 'from', 829 | documentation: 'The placeholder values as a hash', 830 | }, 831 | ], 832 | return: 'string', 833 | }, 834 | { 835 | label: 'number_format', 836 | documentation: { 837 | kind: MarkupKind.Markdown, 838 | value: [ 839 | 'Number format filter.', 840 | '', 841 | 'All of the formatting options can be left null, in that case the defaults will be used. Supplying any of the parameters will override the defaults set in the environment object.', 842 | ].join('\n'), 843 | }, 844 | parameters: [ 845 | { 846 | label: 'int $decimal', 847 | documentation: 'The number of decimal points to display', 848 | }, 849 | { 850 | label: 'string $decimalPoint', 851 | documentation: 'The character(s) to use for the decimal point', 852 | }, 853 | { 854 | label: 'string $thousandSep', 855 | documentation: 'The character(s) to use for the thousands separator', 856 | }, 857 | ], 858 | return: 'string', 859 | }, 860 | { 861 | label: 'abs', 862 | documentation: { 863 | kind: MarkupKind.Markdown, 864 | value: ['Absolute value'].join('\n'), 865 | }, 866 | return: 'int|float', 867 | }, 868 | { 869 | label: 'round', 870 | documentation: { 871 | kind: MarkupKind.Markdown, 872 | value: ['Rounds a number.'].join('\n'), 873 | }, 874 | parameters: [ 875 | { 876 | label: 'int|float $precision', 877 | documentation: 'The rounding precision', 878 | }, 879 | { 880 | label: 'string $method', 881 | documentation: 'The method to use for rounding', 882 | }, 883 | ], 884 | return: 'int|float', 885 | }, 886 | { 887 | label: 'url_encode', 888 | documentation: { 889 | kind: MarkupKind.Markdown, 890 | value: [ 891 | 'URL encodes (RFC 3986) a string as a path segment or an array as a query string.', 892 | ].join('\n'), 893 | }, 894 | return: 'string', 895 | }, 896 | { 897 | label: 'json_encode', 898 | documentation: { 899 | kind: MarkupKind.Markdown, 900 | value: ['Returns the JSON representation of a value'].join('\n'), 901 | }, 902 | parameters: [ 903 | { 904 | label: 'options', 905 | documentation: 906 | "A bitmask of json_encode options: {{data|json_encode(constant('JSON_PRETTY_PRINT')) }}. Combine constants using bitwise operators: {{ data|json_encode(constant('JSON_PRETTY_PRINT') b-or constant('JSON_HEX_QUOT')) }}", 907 | }, 908 | ], 909 | return: 'string|false', 910 | }, 911 | { 912 | label: 'convert_encoding', 913 | documentation: { 914 | kind: MarkupKind.Markdown, 915 | value: [ 916 | 'The convert_encoding filter converts a string from one encoding to another.', 917 | ].join('\n'), 918 | }, 919 | parameters: [ 920 | { 921 | label: 'string $to', 922 | documentation: 'The output charset', 923 | }, 924 | { 925 | label: 'string $from', 926 | documentation: 'The input charset', 927 | }, 928 | ], 929 | return: 'string', 930 | }, 931 | { 932 | label: 'title', 933 | documentation: { 934 | kind: MarkupKind.Markdown, 935 | value: ['Returns a titlecased string.'].join('\n'), 936 | }, 937 | return: 'string', 938 | }, 939 | { 940 | label: 'capitalize', 941 | documentation: { 942 | kind: MarkupKind.Markdown, 943 | value: ['Returns a capitalized string.'].join('\n'), 944 | }, 945 | return: 'string', 946 | }, 947 | { 948 | label: 'upper', 949 | documentation: { 950 | kind: MarkupKind.Markdown, 951 | value: ['Converts a string to uppercase.'].join('\n'), 952 | }, 953 | return: 'string', 954 | }, 955 | { 956 | label: 'lower', 957 | documentation: { 958 | kind: MarkupKind.Markdown, 959 | value: ['Converts a string to lowercase.'].join('\n'), 960 | }, 961 | return: 'string', 962 | }, 963 | { 964 | label: 'striptags', 965 | documentation: { 966 | kind: MarkupKind.Markdown, 967 | value: ['Strips HTML and PHP tags from a string.'].join('\n'), 968 | }, 969 | parameters: [ 970 | { 971 | label: 'string[]|string|null $allowable_tags', 972 | documentation: 'Tags which should not be stripped', 973 | }, 974 | ], 975 | return: 'string', 976 | }, 977 | { 978 | label: 'trim', 979 | documentation: { 980 | kind: MarkupKind.Markdown, 981 | value: ['Returns a trimmed string.'].join('\n'), 982 | }, 983 | parameters: [ 984 | { 985 | label: 'string|null $characterMask', 986 | }, 987 | { 988 | label: "string $side = 'both'", 989 | }, 990 | ], 991 | return: 'string', 992 | }, 993 | { 994 | label: 'nl2br', 995 | documentation: { 996 | kind: MarkupKind.Markdown, 997 | value: ['Inserts HTML line breaks before all newlines in a string.'].join( 998 | '\n' 999 | ), 1000 | }, 1001 | return: 'string', 1002 | }, 1003 | { 1004 | label: 'spaceless', 1005 | documentation: { 1006 | kind: MarkupKind.Markdown, 1007 | value: ['Removes whitespaces between HTML tags.'].join('\n'), 1008 | }, 1009 | return: 'string', 1010 | }, 1011 | { 1012 | label: 'join', 1013 | documentation: { 1014 | kind: MarkupKind.Markdown, 1015 | value: [ 1016 | 'Joins the values to a string.', 1017 | '', 1018 | 'The separators between elements are empty strings per default, you can define them with the optional parameters.', 1019 | '```twig', 1020 | "{{ [1, 2, 3]|join(', ', ' and ') }}", 1021 | '{# returns 1, 2 and 3 #}', 1022 | '```', 1023 | ].join('\n'), 1024 | }, 1025 | parameters: [ 1026 | { 1027 | label: 'string $glue', 1028 | documentation: 'The separator', 1029 | }, 1030 | { 1031 | label: 'string|null $and = null', 1032 | documentation: 'The separator for the last pair', 1033 | }, 1034 | ], 1035 | return: 'string', 1036 | }, 1037 | { 1038 | label: 'split', 1039 | documentation: { 1040 | kind: MarkupKind.Markdown, 1041 | value: [ 1042 | 'Splits the string into an array.', 1043 | '', 1044 | '```twig', 1045 | '{{ "one,two,three"|split(\',\') }}', 1046 | '{# returns [one, two, three] #}', 1047 | '```', 1048 | ].join('\n'), 1049 | }, 1050 | parameters: [ 1051 | { 1052 | label: 'string $delimiter', 1053 | documentation: 'The delimiter', 1054 | }, 1055 | { 1056 | label: 'int $limit', 1057 | documentation: 'The limit', 1058 | }, 1059 | ], 1060 | return: 'array', 1061 | }, 1062 | { 1063 | label: 'sort', 1064 | documentation: { 1065 | kind: MarkupKind.Markdown, 1066 | value: ['Sorts an array.'].join('\n'), 1067 | }, 1068 | return: 'array', 1069 | }, 1070 | { 1071 | label: 'merge', 1072 | documentation: { 1073 | kind: MarkupKind.Markdown, 1074 | value: [ 1075 | 'Merges any number of arrays or Traversable objects.', 1076 | '', 1077 | '```twig', 1078 | "{% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}", 1079 | '', 1080 | "{% set items = items|merge({ 'peugeot': 'car' }, { 'banana': 'fruit' }) %}", 1081 | '', 1082 | "{# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'banana': 'fruit' } #}", 1083 | '```', 1084 | ].join('\n'), 1085 | }, 1086 | return: 'array', 1087 | }, 1088 | { 1089 | label: 'batch', 1090 | documentation: { 1091 | kind: MarkupKind.Markdown, 1092 | value: [ 1093 | 'Batches item.', 1094 | '', 1095 | '```twig', 1096 | "{% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}", 1097 | '', 1098 | "{% set items = items|merge({ 'peugeot': 'car' }, { 'banana': 'fruit' }) %}", 1099 | '', 1100 | "{# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'banana': 'fruit' } #}", 1101 | '```', 1102 | ].join('\n'), 1103 | }, 1104 | parameters: [ 1105 | { 1106 | label: 'int $size', 1107 | documentation: 'The size of the batch', 1108 | }, 1109 | { 1110 | label: 'mixed $fill', 1111 | documentation: 'A value used to fill missing items', 1112 | }, 1113 | ], 1114 | return: 'array', 1115 | }, 1116 | { 1117 | label: 'column', 1118 | documentation: { 1119 | kind: MarkupKind.Markdown, 1120 | value: [ 1121 | 'Returns the values from a single column in the input array.', 1122 | '', 1123 | '```twig', 1124 | '
',
1125 |         "  {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}",
1126 |         '',
1127 |         "  {% set fruits = items|column('fruit') %}",
1128 |         '',
1129 |         "  {# fruits now contains ['apple', 'orange'] #}",
1130 |         '
', 1131 | '```', 1132 | ].join('\n'), 1133 | }, 1134 | parameters: [ 1135 | { 1136 | label: 'mixed $name', 1137 | documentation: 'The column name', 1138 | }, 1139 | { 1140 | label: 'mixed $index', 1141 | documentation: 1142 | 'The column to use as the index/keys for the returned array', 1143 | }, 1144 | ], 1145 | return: 'array', 1146 | }, 1147 | { 1148 | label: 'filter', 1149 | documentation: { 1150 | kind: MarkupKind.Markdown, 1151 | value: [ 1152 | 'The `filter` filter filters elements of a sequence or a mapping using an arrow function.', 1153 | ].join('\n'), 1154 | }, 1155 | parameters: [ 1156 | { 1157 | label: 'arrow', 1158 | documentation: 'The arrow function', 1159 | }, 1160 | ], 1161 | return: 'array', 1162 | }, 1163 | { 1164 | label: 'map', 1165 | documentation: { 1166 | kind: MarkupKind.Markdown, 1167 | value: [ 1168 | 'The `map` filter applies an arrow function to the elements of a sequence or a mapping.', 1169 | ].join('\n'), 1170 | }, 1171 | parameters: [ 1172 | { 1173 | label: 'arrow', 1174 | documentation: 'The arrow function', 1175 | }, 1176 | ], 1177 | return: 'array', 1178 | }, 1179 | { 1180 | label: 'reduce', 1181 | documentation: { 1182 | kind: MarkupKind.Markdown, 1183 | value: [ 1184 | 'The `reduce` filter iteratively reduces a sequence or a mapping to a single value using an arrow function, so as to reduce it to a single value.', 1185 | ].join('\n'), 1186 | }, 1187 | parameters: [ 1188 | { 1189 | label: 'arrow', 1190 | documentation: 'The arrow function', 1191 | }, 1192 | { 1193 | label: 'initial', 1194 | documentation: 'The initial value', 1195 | }, 1196 | ], 1197 | return: 'array', 1198 | }, 1199 | { 1200 | label: 'reverse', 1201 | documentation: { 1202 | kind: MarkupKind.Markdown, 1203 | value: ['Reverses a variable.'].join('\n'), 1204 | }, 1205 | parameters: [ 1206 | { 1207 | label: 'bool $preserveKeys', 1208 | documentation: 'Whether to preserve key or not', 1209 | }, 1210 | ], 1211 | return: 'mixed', 1212 | }, 1213 | { 1214 | label: 'length', 1215 | documentation: { 1216 | kind: MarkupKind.Markdown, 1217 | value: ['Slices a variable.'].join('\n'), 1218 | }, 1219 | return: 'int', 1220 | }, 1221 | { 1222 | label: 'slice', 1223 | documentation: { 1224 | kind: MarkupKind.Markdown, 1225 | value: ['Returns the length of a variable.'].join('\n'), 1226 | }, 1227 | parameters: [ 1228 | { 1229 | label: 'int $start', 1230 | documentation: 'Start of the slice', 1231 | }, 1232 | { 1233 | label: 'int $length', 1234 | documentation: 'Size of the slice', 1235 | }, 1236 | { 1237 | label: 'bool $preserveKeys', 1238 | documentation: 1239 | 'Whether to preserve key or not (when the input is an array)', 1240 | }, 1241 | ], 1242 | return: 'mixed', 1243 | }, 1244 | { 1245 | label: 'first', 1246 | documentation: { 1247 | kind: MarkupKind.Markdown, 1248 | value: ['Returns the first element of the item.'].join('\n'), 1249 | }, 1250 | return: 'mixed', 1251 | }, 1252 | { 1253 | label: 'last', 1254 | documentation: { 1255 | kind: MarkupKind.Markdown, 1256 | value: ['Returns the last element of the item.'].join('\n'), 1257 | }, 1258 | return: 'mixed', 1259 | }, 1260 | { 1261 | label: 'default', 1262 | documentation: { 1263 | kind: MarkupKind.Markdown, 1264 | value: [ 1265 | 'The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable', 1266 | ].join('\n'), 1267 | }, 1268 | parameters: [ 1269 | { 1270 | label: 'default', 1271 | documentation: 'The default value', 1272 | }, 1273 | ], 1274 | return: 'mixed', 1275 | }, 1276 | { 1277 | label: 'keys', 1278 | documentation: { 1279 | kind: MarkupKind.Markdown, 1280 | value: ['Returns the keys for the given array.'].join('\n'), 1281 | }, 1282 | return: 'array', 1283 | }, 1284 | { 1285 | label: 'data_uri', 1286 | documentation: { 1287 | kind: MarkupKind.Markdown, 1288 | value: [ 1289 | 'Creates a data URI (RFC 2397).', 1290 | 'Length validation is not performed on purpose, validation should be done before calling this filter.', 1291 | ].join('\n'), 1292 | }, 1293 | return: 'string', 1294 | }, 1295 | { 1296 | label: 'escape', 1297 | documentation: { 1298 | kind: MarkupKind.Markdown, 1299 | value: ['Escapes a string.'].join('\n'), 1300 | }, 1301 | parameters: [ 1302 | { 1303 | label: 'string $strategy', 1304 | documentation: 'The escaping strategy', 1305 | }, 1306 | { 1307 | label: 'string $charset', 1308 | documentation: 'The charset', 1309 | }, 1310 | { 1311 | label: 'bool $autoescape', 1312 | documentation: 1313 | 'Whether the function is called by the auto-escaping feature (true) or by the developer (false)', 1314 | }, 1315 | ], 1316 | return: 'string', 1317 | }, 1318 | { 1319 | label: 'e', 1320 | documentation: { 1321 | kind: MarkupKind.Markdown, 1322 | value: ['Escapes a string.'].join('\n'), 1323 | }, 1324 | parameters: [ 1325 | { 1326 | label: 'string $strategy', 1327 | documentation: 'The escaping strategy', 1328 | }, 1329 | { 1330 | label: 'string $charset', 1331 | documentation: 'The charset', 1332 | }, 1333 | { 1334 | label: 'bool $autoescape', 1335 | documentation: 1336 | 'Whether the function is called by the auto-escaping feature (true) or by the developer (false)', 1337 | }, 1338 | ], 1339 | return: 'string', 1340 | }, 1341 | { 1342 | label: 'raw', 1343 | documentation: { 1344 | kind: MarkupKind.Markdown, 1345 | value: ['Marks a variable as being safe.'].join('\n'), 1346 | }, 1347 | return: 'string', 1348 | }, 1349 | { 1350 | label: 'inky_to_html', 1351 | documentation: { 1352 | kind: MarkupKind.Markdown, 1353 | value: ['Marks a variable as being safe.'].join('\n'), 1354 | }, 1355 | return: 'string', 1356 | }, 1357 | { 1358 | label: 'country_name', 1359 | documentation: { 1360 | kind: MarkupKind.Markdown, 1361 | value: [ 1362 | 'The `country_name` filter returns the country name given its ISO-3166 two-letter code', 1363 | ].join('\n'), 1364 | }, 1365 | return: 'string', 1366 | }, 1367 | { 1368 | label: 'currency_name', 1369 | documentation: { 1370 | kind: MarkupKind.Markdown, 1371 | value: [ 1372 | 'The `currency_name` filter returns the currency name given its three-letter code', 1373 | ].join('\n'), 1374 | }, 1375 | return: 'string', 1376 | }, 1377 | { 1378 | label: 'currency_symbol', 1379 | documentation: { 1380 | kind: MarkupKind.Markdown, 1381 | value: [ 1382 | 'The currency_symbol filter returns the currency symbol given its three-letter code', 1383 | ].join('\n'), 1384 | }, 1385 | return: 'string', 1386 | }, 1387 | { 1388 | label: 'language_name', 1389 | documentation: { 1390 | kind: MarkupKind.Markdown, 1391 | value: [ 1392 | 'The `language_name` filter returns the language name given its two-letter code', 1393 | ].join('\n'), 1394 | }, 1395 | return: 'string', 1396 | }, 1397 | { 1398 | label: 'locale_name', 1399 | documentation: { 1400 | kind: MarkupKind.Markdown, 1401 | value: [ 1402 | 'The `locale_name` filter returns the locale name given its two-letter code', 1403 | ].join('\n'), 1404 | }, 1405 | return: 'string', 1406 | }, 1407 | { 1408 | label: 'timezone_name', 1409 | documentation: { 1410 | kind: MarkupKind.Markdown, 1411 | value: [ 1412 | 'The `timezone_name` filter returns the timezone name given a timezone identifier', 1413 | ].join('\n'), 1414 | }, 1415 | return: 'string', 1416 | }, 1417 | { 1418 | label: 'format_currency', 1419 | documentation: { 1420 | kind: MarkupKind.Markdown, 1421 | value: [ 1422 | 'The `format_currency` filter formats a number as a currency', 1423 | ].join('\n'), 1424 | }, 1425 | parameters: [ 1426 | { 1427 | label: 'currency', 1428 | documentation: 'The currency', 1429 | }, 1430 | { 1431 | label: 'attrs', 1432 | documentation: 'A map of attributes', 1433 | }, 1434 | { 1435 | label: 'locale', 1436 | documentation: 'The locale', 1437 | }, 1438 | ], 1439 | return: 'string', 1440 | }, 1441 | { 1442 | label: 'format_number', 1443 | documentation: { 1444 | kind: MarkupKind.Markdown, 1445 | value: ['The `format_number` filter formats a number'].join('\n'), 1446 | }, 1447 | parameters: [ 1448 | { 1449 | label: 'locale', 1450 | documentation: 'The locale', 1451 | }, 1452 | { 1453 | label: 'attrs', 1454 | documentation: 'A map of attributes', 1455 | }, 1456 | { 1457 | label: 'style', 1458 | documentation: 'The style of the number output', 1459 | }, 1460 | ], 1461 | return: 'string', 1462 | }, 1463 | { 1464 | label: 'format_datetime', 1465 | documentation: { 1466 | kind: MarkupKind.Markdown, 1467 | value: ['The `format_datetime` filter formats a date time'].join('\n'), 1468 | }, 1469 | return: 'string', 1470 | }, 1471 | { 1472 | label: 'format_date', 1473 | documentation: { 1474 | kind: MarkupKind.Markdown, 1475 | value: [ 1476 | 'The `format_date` filter formats a date. It behaves in the exact same way as the format_datetime filter, but without the time.', 1477 | ].join('\n'), 1478 | }, 1479 | return: 'string', 1480 | }, 1481 | { 1482 | label: 'format_time', 1483 | documentation: { 1484 | kind: MarkupKind.Markdown, 1485 | value: [ 1486 | 'The `format_time` filter formats a time. It behaves in the exact same way as the format_datetime filter, but without the date.', 1487 | ].join('\n'), 1488 | }, 1489 | return: 'string', 1490 | }, 1491 | { 1492 | label: 'markdown_to_html', 1493 | documentation: { 1494 | kind: MarkupKind.Markdown, 1495 | value: [ 1496 | 'The `markdown_to_html` filter converts a block of Markdown to HTML', 1497 | ].join('\n'), 1498 | }, 1499 | }, 1500 | { 1501 | label: 'html_to_markdown', 1502 | documentation: { 1503 | kind: MarkupKind.Markdown, 1504 | value: [ 1505 | 'The `html_to_markdown` filter converts a block of HTML to Markdown', 1506 | ].join('\n'), 1507 | }, 1508 | }, 1509 | { 1510 | label: 'slug', 1511 | documentation: { 1512 | kind: MarkupKind.Markdown, 1513 | value: [ 1514 | 'The slug filter transforms a given string into another string that only includes safe ASCII characters.', 1515 | ].join('\n'), 1516 | }, 1517 | parameters: [ 1518 | { 1519 | label: 'separator', 1520 | documentation: 1521 | 'The separator that is used to join words (defaults to -)', 1522 | }, 1523 | { 1524 | label: 'locale', 1525 | documentation: 1526 | 'The locale of the original string (if none is specified, it will be automatically detected)', 1527 | }, 1528 | ], 1529 | return: 'string', 1530 | }, 1531 | { 1532 | label: 'u', 1533 | documentation: { 1534 | kind: MarkupKind.Markdown, 1535 | value: [ 1536 | 'The `u` filter wraps a text in a Unicode object (a Symfony UnicodeString instance) that exposes methods to "manipulate" the string.', 1537 | ].join('\n'), 1538 | }, 1539 | }, 1540 | { 1541 | label: 'abbr_class', 1542 | }, 1543 | { 1544 | label: 'abbr_method', 1545 | }, 1546 | { 1547 | label: 'file_excerpt', 1548 | }, 1549 | { 1550 | label: 'file_link', 1551 | }, 1552 | { 1553 | label: 'file_relative', 1554 | }, 1555 | { 1556 | label: 'format_args', 1557 | }, 1558 | { 1559 | label: 'format_args_as_text', 1560 | }, 1561 | { 1562 | label: 'format_file', 1563 | }, 1564 | { 1565 | label: 'format_file_from_text', 1566 | }, 1567 | { 1568 | label: 'humanize', 1569 | }, 1570 | { 1571 | label: 'sanitize_html', 1572 | }, 1573 | { 1574 | label: 'serialize', 1575 | }, 1576 | { 1577 | label: 'trans', 1578 | }, 1579 | { 1580 | label: 'yaml_dump', 1581 | }, 1582 | { 1583 | label: 'yaml_encode', 1584 | }, 1585 | ]; 1586 | 1587 | export const twigFunctionsSignatureInformation = new Map< 1588 | string, 1589 | SignatureInformation 1590 | >( 1591 | twigFunctions.map((item) => { 1592 | const label = item.label; 1593 | const params = item.parameters?.map((item) => item.label).join(', '); 1594 | const signatureInformation: SignatureInformation = { 1595 | label: `${item.label}(${params ?? ''})`, 1596 | parameters: item.parameters, 1597 | }; 1598 | 1599 | if (item.return) { 1600 | signatureInformation.label += `: ${item.return}`; 1601 | } 1602 | 1603 | return [label, signatureInformation]; 1604 | }) 1605 | ); 1606 | 1607 | export const forLoopProperties: CompletionItem[] = [ 1608 | { 1609 | label: 'index', 1610 | detail: 'The current iteration of the loop. (1 indexed)', 1611 | kind: CompletionItemKind.Property, 1612 | }, 1613 | { 1614 | label: 'index0', 1615 | detail: 'The current iteration of the loop. (0 indexed)', 1616 | kind: CompletionItemKind.Property, 1617 | }, 1618 | { 1619 | label: 'revindex', 1620 | detail: 'The number of iterations from the end of the loop (1 indexed)', 1621 | kind: CompletionItemKind.Property, 1622 | }, 1623 | { 1624 | label: 'revindex0', 1625 | detail: 'The number of iterations from the end of the loop (0 indexed)', 1626 | kind: CompletionItemKind.Property, 1627 | }, 1628 | { 1629 | label: 'first', 1630 | detail: 'True if first iteration', 1631 | kind: CompletionItemKind.Property, 1632 | }, 1633 | { 1634 | label: 'last', 1635 | detail: 'True if last iteration', 1636 | kind: CompletionItemKind.Property, 1637 | }, 1638 | { 1639 | label: 'length', 1640 | detail: 'The number of items in the sequence', 1641 | kind: CompletionItemKind.Property, 1642 | }, 1643 | { 1644 | label: 'parent', 1645 | detail: 'The parent context', 1646 | kind: CompletionItemKind.Property, 1647 | }, 1648 | ]; 1649 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/completion-provider.ts: -------------------------------------------------------------------------------- 1 | import { CompletionItem, CompletionParams } from 'vscode-languageserver/node'; 2 | import { Server } from '../server'; 3 | import { findNodeByPosition } from '../utils/find-element-by-position'; 4 | import { templatePaths } from './template-paths'; 5 | import { globalVariables } from './global-variables'; 6 | import { localVariables } from './local-variables'; 7 | import { functions } from './functions'; 8 | import { filters } from './filters'; 9 | import { forLoop } from './for-loop'; 10 | 11 | export class CompletionProvider { 12 | server: Server; 13 | 14 | constructor(server: Server) { 15 | this.server = server; 16 | 17 | this.server.connection.onCompletion(this.onCompletion.bind(this)); 18 | this.server.connection.onCompletionResolve( 19 | this.onCompletionResolve.bind(this) 20 | ); 21 | } 22 | 23 | async onCompletion(params: CompletionParams) { 24 | let completions: CompletionItem[] = []; 25 | const uri = params.textDocument.uri; 26 | const document = this.server.documentCache.getDocument(uri); 27 | 28 | if (!document) { 29 | return; 30 | } 31 | 32 | const cst = await document.cst(); 33 | const cursorNode = findNodeByPosition(cst.rootNode, params.position); 34 | 35 | if (!cursorNode) { 36 | return; 37 | } 38 | 39 | [ 40 | globalVariables(cursorNode), 41 | functions(cursorNode), 42 | filters(cursorNode), 43 | localVariables(cursorNode), 44 | forLoop(cursorNode), 45 | templatePaths( 46 | cursorNode, 47 | uri, 48 | this.server.documentCache.documents.keys() 49 | ), 50 | ].forEach((result) => { 51 | if (Array.isArray(result)) { 52 | completions.push(...result); 53 | } 54 | }); 55 | 56 | return completions; 57 | } 58 | 59 | async onCompletionResolve(item: CompletionItem): Promise { 60 | return Promise.resolve(item); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/filters.ts: -------------------------------------------------------------------------------- 1 | import { CompletionItem, CompletionItemKind } from 'vscode-languageserver/node'; 2 | import { SyntaxNode } from 'web-tree-sitter'; 3 | import { twigFilters } from '../common'; 4 | 5 | const completions: CompletionItem[] = twigFilters.map((item) => 6 | Object.assign({}, item, { 7 | kind: CompletionItemKind.Function, 8 | detail: 'filter', 9 | }) 10 | ); 11 | 12 | export function filters(cursorNode: SyntaxNode) { 13 | if (cursorNode.text === '|') { 14 | return completions; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/for-loop.ts: -------------------------------------------------------------------------------- 1 | import { CompletionItemKind } from 'vscode-languageserver/node'; 2 | import { SyntaxNode } from 'web-tree-sitter'; 3 | import { forLoopProperties } from '../common'; 4 | import { findParentByType } from '../utils/find-parent-by-type'; 5 | 6 | export function forLoop(cursorNode: SyntaxNode) { 7 | if (!findParentByType(cursorNode, 'for')) { 8 | return; 9 | } 10 | 11 | if ( 12 | cursorNode.text === '.' && 13 | cursorNode.previousSibling?.type === 'variable' && 14 | cursorNode.previousSibling.text === 'loop' 15 | ) { 16 | return forLoopProperties; 17 | } 18 | 19 | if (cursorNode.type === 'variable') { 20 | return [ 21 | { 22 | label: 'loop', 23 | kind: CompletionItemKind.Variable, 24 | }, 25 | ]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/functions.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Command, 3 | CompletionItem, 4 | CompletionItemKind, 5 | InsertTextFormat, 6 | } from 'vscode-languageserver/node'; 7 | import { SyntaxNode } from 'web-tree-sitter'; 8 | import { twigFunctions } from '../common'; 9 | import { isEmptyEmbedded } from '../utils/is-empty-embedded'; 10 | 11 | const triggerParameterHints = Command.create( 12 | 'Trigger parameter hints', 13 | 'editor.action.triggerParameterHints' 14 | ); 15 | 16 | const completions: CompletionItem[] = twigFunctions.map((item) => 17 | Object.assign({}, item, { 18 | kind: CompletionItemKind.Function, 19 | insertText: `${item.label}($1)$0`, 20 | insertTextFormat: InsertTextFormat.Snippet, 21 | command: triggerParameterHints, 22 | detail: 'function', 23 | }) 24 | ); 25 | 26 | export function functions(cursorNode: SyntaxNode) { 27 | if (['variable', 'function'].includes(cursorNode.type) || isEmptyEmbedded(cursorNode)) { 28 | return completions; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/global-variables.ts: -------------------------------------------------------------------------------- 1 | import { CompletionItem, CompletionItemKind } from 'vscode-languageserver/node'; 2 | import { SyntaxNode } from 'web-tree-sitter'; 3 | import { twigGlobalVariables } from '../common'; 4 | import { isEmptyEmbedded } from '../utils/is-empty-embedded'; 5 | 6 | const completions: CompletionItem[] = twigGlobalVariables.map((item) => 7 | Object.assign({}, item, { 8 | kind: CompletionItemKind.Variable, 9 | detail: 'global variable', 10 | }) 11 | ); 12 | 13 | export function globalVariables(cursorNode: SyntaxNode) { 14 | if (cursorNode.type === 'variable' || isEmptyEmbedded(cursorNode)) { 15 | return completions; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/local-variables.ts: -------------------------------------------------------------------------------- 1 | import { CompletionItem, CompletionItemKind } from 'vscode-languageserver/node'; 2 | import { SyntaxNode } from 'web-tree-sitter'; 3 | import { bottomTopCursorIterator } from '../utils/bottom-top-cursor-iterator'; 4 | 5 | export function localVariables(cursorNode: SyntaxNode) { 6 | if (cursorNode.type !== 'variable') { 7 | return; 8 | } 9 | 10 | let completions: CompletionItem[] = []; 11 | 12 | for (let node of bottomTopCursorIterator(cursorNode)) { 13 | if (node.type === 'set') { 14 | let cursor = node.walk(); 15 | 16 | cursor.gotoFirstChild(); 17 | 18 | while (cursor.gotoNextSibling()) { 19 | if (cursor.currentFieldName() === 'variable') { 20 | completions.push({ 21 | label: cursor.nodeText, 22 | kind: CompletionItemKind.Variable, 23 | }); 24 | } 25 | } 26 | } 27 | } 28 | 29 | return completions; 30 | } 31 | -------------------------------------------------------------------------------- /packages/language-server/src/completions/template-paths.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CompletionItem, 3 | CompletionItemKind, 4 | DocumentUri, 5 | } from 'vscode-languageserver/node'; 6 | import { documentUriToFsPath } from '../utils/document-uri-to-fs-path'; 7 | import { dirname, relative } from 'path'; 8 | import { trimTwigExtension } from '../utils/trim-twig-extension'; 9 | import { SyntaxNode } from 'web-tree-sitter'; 10 | import { templateUsingFunctions, templateUsingStatements } from '../constants/template-usage'; 11 | 12 | export function templatePaths( 13 | cursorNode: SyntaxNode, 14 | currentDocumentUri: DocumentUri, 15 | documentsPaths: IterableIterator 16 | ) { 17 | if (cursorNode.type !== 'string') { 18 | return; 19 | } 20 | 21 | const completions: CompletionItem[] = []; 22 | let node = cursorNode.parent; 23 | 24 | if (!node) { 25 | return; 26 | } 27 | 28 | // This case for array or ternary wrappers 29 | // ['template.html'] 30 | // ajax ? 'ajax.html' : 'not_ajax.html' 31 | if (['array', 'ternary'].includes(node.type)) { 32 | node = node.parent; 33 | } 34 | 35 | if (!node) { 36 | return; 37 | } 38 | 39 | if ( 40 | // {% import "forms.html" as forms %} 41 | // {% from "macros.twig" import hello %} 42 | // {% include 'template.html' %} 43 | // {% extends 'template.html' %} 44 | // {% use 'template.html' %} 45 | templateUsingStatements.includes(node.type) || 46 | // {{ include('template.html') }} 47 | // {{ source('template.html') }} 48 | (node.type === 'arguments' && 49 | templateUsingFunctions.includes( 50 | node.parent?.childForFieldName('name')?.text || '' 51 | )) || 52 | // {{ block("title", "common_blocks.twig") }} 53 | (node.type === 'arguments' && 54 | node.parent?.childForFieldName('name')?.text === 'block' && 55 | cursorNode?.equals(node.namedChildren[1])) 56 | ) { 57 | const currentPath = dirname(documentUriToFsPath(currentDocumentUri)); 58 | 59 | for (const twigPath of documentsPaths) { 60 | completions.push({ 61 | label: relative( 62 | currentPath, 63 | documentUriToFsPath(trimTwigExtension(twigPath)) 64 | ), 65 | kind: CompletionItemKind.File, 66 | }); 67 | } 68 | } 69 | 70 | return completions; 71 | } 72 | -------------------------------------------------------------------------------- /packages/language-server/src/configuration/configuration-manager.ts: -------------------------------------------------------------------------------- 1 | import { DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver'; 2 | import { Server } from '../server'; 3 | import { LanguageServerSettings } from './language-server-settings'; 4 | import { getTemplatePathMappingsFromSymfony } from '../utils/symfony/twigConfig'; 5 | 6 | export class ConfigurationManager { 7 | readonly configurationSection = 'modernTwig'; 8 | server: Server; 9 | 10 | constructor(server: Server) { 11 | this.server = server; 12 | 13 | this.server.connection.client.register(DidChangeConfigurationNotification.type, { section: this.configurationSection }); 14 | this.server.connection.onDidChangeConfiguration(this.onDidChangeConfiguration.bind(this)); 15 | } 16 | 17 | async onDidChangeConfiguration({ settings }: DidChangeConfigurationParams) { 18 | const config: LanguageServerSettings | undefined = settings?.[this.configurationSection]; 19 | 20 | const phpBinConsoleCommand = config?.phpBinConsoleCommand?.trim(); 21 | const mappings = phpBinConsoleCommand 22 | ? await getTemplatePathMappingsFromSymfony(phpBinConsoleCommand) 23 | : []; 24 | 25 | this.server.definitionProvider.templateMappings = mappings; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/language-server/src/configuration/language-server-settings.ts: -------------------------------------------------------------------------------- 1 | export type LanguageServerSettings = { 2 | phpBinConsoleCommand: string, 3 | }; 4 | -------------------------------------------------------------------------------- /packages/language-server/src/constants/template-usage.ts: -------------------------------------------------------------------------------- 1 | 2 | export const templateUsingFunctions = [ 3 | 'include', 4 | 'source', 5 | ]; 6 | 7 | export const templateUsingStatements = [ 8 | 'import', 9 | 'from', 10 | 'include', 11 | 'extends', 12 | 'use', 13 | ]; 14 | -------------------------------------------------------------------------------- /packages/language-server/src/definitions/definition-provider.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Connection, 3 | Definition, 4 | DefinitionParams, 5 | DocumentUri, 6 | Range, 7 | } from 'vscode-languageserver'; 8 | import { Server } from '../server'; 9 | import { SyntaxNode } from 'web-tree-sitter'; 10 | import { 11 | templateUsingFunctions, 12 | templateUsingStatements, 13 | } from '../constants/template-usage'; 14 | import { getStringNodeValue } from '../utils/node'; 15 | import { TemplatePathMapping } from '../utils/symfony/twigConfig'; 16 | import { documentUriToFsPath } from '../utils/document-uri-to-fs-path'; 17 | import { fileStat } from '../utils/files/fileStat'; 18 | import * as path from 'path'; 19 | import { fsPathToDocumentUri } from '../utils/fs-path-to-document-uri'; 20 | import { findNodeByPosition } from '../utils/find-element-by-position'; 21 | 22 | export type onDefinitionHandlerReturn = ReturnType< 23 | Parameters[0] 24 | >; 25 | 26 | const isFunctionCall = ( 27 | node: SyntaxNode | null, 28 | functionName: string 29 | ): boolean => { 30 | return ( 31 | !!node && 32 | node.type === 'call_expression' && 33 | node.childForFieldName('name')?.text === functionName 34 | ); 35 | }; 36 | 37 | const isPathInsideTemplateEmbedding = (node: SyntaxNode): boolean => { 38 | if (node.type !== 'string' || !node.parent) { 39 | return false; 40 | } 41 | 42 | const isInsideStatement = templateUsingStatements.includes(node.parent.type); 43 | 44 | if (isInsideStatement) { 45 | return true; 46 | } 47 | 48 | const isInsideFunctionCall = 49 | node.parent?.type === 'arguments' && 50 | templateUsingFunctions.some((func) => 51 | isFunctionCall(node.parent!.parent, func) 52 | ); 53 | 54 | return isInsideFunctionCall; 55 | }; 56 | 57 | export class DefinitionProvider { 58 | server: Server; 59 | 60 | templateMappings: TemplatePathMapping[] = []; 61 | 62 | constructor(server: Server) { 63 | this.server = server; 64 | 65 | this.server.connection.onDefinition(this.onDefinition.bind(this)); 66 | } 67 | 68 | async onDefinition( 69 | params: DefinitionParams 70 | ): Promise { 71 | const document = this.server.documentCache.getDocument(params.textDocument.uri); 72 | 73 | if (!document) { 74 | return; 75 | } 76 | 77 | const cst = await document.cst(); 78 | 79 | const cursorNode = findNodeByPosition( 80 | cst.rootNode, 81 | params.position 82 | ); 83 | 84 | if (!cursorNode) { 85 | return; 86 | } 87 | 88 | if (isPathInsideTemplateEmbedding(cursorNode)) { 89 | const templateUri = await this.resolveTemplateUri( 90 | getStringNodeValue(cursorNode) 91 | ); 92 | 93 | if (!templateUri) return; 94 | 95 | return this.resolveTemplateDefinition(templateUri); 96 | } 97 | } 98 | 99 | async resolveTemplateUri( 100 | includeArgument: string 101 | ): Promise { 102 | const workspaceFolderDirectory = documentUriToFsPath( 103 | this.server.workspaceFolder.uri 104 | ); 105 | 106 | for (const { namespace, directory } of this.templateMappings) { 107 | if (!includeArgument.startsWith(namespace)) { 108 | continue; 109 | } 110 | 111 | const includePath = 112 | namespace === '' 113 | ? path.join(directory, includeArgument) 114 | : includeArgument.replace(namespace, directory); 115 | 116 | const pathToTwig = path.resolve(workspaceFolderDirectory, includePath); 117 | 118 | const stats = await fileStat(pathToTwig); 119 | if (stats) { 120 | return fsPathToDocumentUri(pathToTwig); 121 | } 122 | } 123 | 124 | return undefined; 125 | } 126 | 127 | resolveTemplateDefinition(templatePath: string): Definition | undefined { 128 | const document = this.server.documentCache.getDocument(templatePath); 129 | 130 | if (!document) { 131 | return; 132 | } 133 | 134 | return { 135 | uri: fsPathToDocumentUri(document.filePath), 136 | range: Range.create(0, 0, 0, 0), 137 | }; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /packages/language-server/src/document-cache.ts: -------------------------------------------------------------------------------- 1 | import { URI } from 'vscode-uri'; 2 | import readDir from './utils/read-dir'; 3 | import { parseTwig } from './utils/parse-twig'; 4 | import { readFile } from 'fs/promises'; 5 | import { DocumentUri, WorkspaceFolder } from 'vscode-languageserver'; 6 | import { fsPathToDocumentUri } from './utils/fs-path-to-document-uri'; 7 | import Parser from 'web-tree-sitter'; 8 | 9 | export class Document { 10 | filePath: string; 11 | text: string | null = null; 12 | 13 | constructor(filePath: string) { 14 | this.filePath = filePath; 15 | } 16 | 17 | async setText(text: string) { 18 | this.text = text; 19 | } 20 | 21 | async getText() { 22 | if (this.text) { 23 | return Promise.resolve(this.text); 24 | } 25 | 26 | return await readFile(this.filePath, 'utf-8'); 27 | } 28 | 29 | async cst(): Promise { 30 | const text = await this.getText(); 31 | 32 | return await parseTwig(text); 33 | } 34 | } 35 | 36 | export class DocumentCache { 37 | workspaceFolder!: WorkspaceFolder; 38 | documents: Map = new Map(); 39 | 40 | constructor(workspaceFolder: WorkspaceFolder) { 41 | this.workspaceFolder = workspaceFolder; 42 | 43 | this.initDocuments(); 44 | } 45 | 46 | async initDocuments() { 47 | const iterator = readDir(URI.parse(this.workspaceFolder.uri).fsPath); 48 | const reIsTwig = /.twig$/i; 49 | 50 | for await (const filePath of iterator) { 51 | if (reIsTwig.test(filePath)) { 52 | this.documents.set( 53 | fsPathToDocumentUri(filePath), 54 | new Document(filePath) 55 | ); 56 | } 57 | } 58 | } 59 | 60 | getDocument(documentUri: DocumentUri) { 61 | return this.documents.get(documentUri); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /packages/language-server/src/hovers/filters.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | import { onHoverHandlerReturn } from './hover-provider'; 3 | import { twigFilters } from '../common'; 4 | 5 | export function filters(cursorNode: SyntaxNode): onHoverHandlerReturn { 6 | if ( 7 | (cursorNode.type === 'variable' || cursorNode.type === 'function') && 8 | cursorNode.previousSibling?.text === '|' 9 | ) { 10 | for (const item of twigFilters) { 11 | if (item.label === cursorNode.text) { 12 | if (item.documentation) { 13 | return { 14 | contents: item.documentation, 15 | }; 16 | } else { 17 | return; 18 | } 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/language-server/src/hovers/for-loop.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | import { onHoverHandlerReturn } from './hover-provider'; 3 | import { forLoopProperties } from '../common'; 4 | import { findParentByType } from '../utils/find-parent-by-type'; 5 | 6 | export function forLoop(cursorNode: SyntaxNode): onHoverHandlerReturn { 7 | if (!findParentByType(cursorNode, 'for')) { 8 | return; 9 | } 10 | 11 | if ( 12 | cursorNode.type === 'property' && 13 | cursorNode.previousSibling?.text === '.' && 14 | cursorNode.previousSibling?.previousSibling?.type === 'variable' && 15 | cursorNode.previousSibling?.previousSibling?.text === 'loop' 16 | ) { 17 | const property = forLoopProperties.find( 18 | (item) => item.label === cursorNode.text 19 | ); 20 | 21 | if (property && property.detail) { 22 | return { 23 | contents: property.detail, 24 | }; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/language-server/src/hovers/functions.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | import { onHoverHandlerReturn } from './hover-provider'; 3 | import { twigFunctions } from '../common'; 4 | 5 | export function functions(cursorNode: SyntaxNode): onHoverHandlerReturn { 6 | if (cursorNode.type === 'variable' || cursorNode.type === 'function') { 7 | for (const item of twigFunctions) { 8 | if (item.label === cursorNode.text) { 9 | if (item.documentation) { 10 | return { 11 | contents: item.documentation, 12 | }; 13 | } else { 14 | return; 15 | } 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /packages/language-server/src/hovers/global-variables.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | import { onHoverHandlerReturn } from './hover-provider'; 3 | import { twigGlobalVariables } from '../common'; 4 | 5 | export function globalVariables(cursorNode: SyntaxNode): onHoverHandlerReturn { 6 | if (cursorNode.type !== 'variable') { 7 | return; 8 | } 9 | 10 | for (const item of twigGlobalVariables) { 11 | if (item.label === cursorNode.text) { 12 | return { 13 | contents: item.documentation, 14 | }; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /packages/language-server/src/hovers/hover-provider.ts: -------------------------------------------------------------------------------- 1 | import { Connection, HoverParams } from 'vscode-languageserver'; 2 | import { Server } from '../server'; 3 | import { findNodeByPosition } from '../utils/find-element-by-position'; 4 | import { twigGlobalVariables } from '../common'; 5 | import { bottomTopCursorIterator } from '../utils/bottom-top-cursor-iterator'; 6 | import { globalVariables } from './global-variables'; 7 | import { localVariables } from './local-variables'; 8 | import { forLoop } from './for-loop'; 9 | import { functions } from './functions'; 10 | import { filters } from './filters'; 11 | 12 | export type onHoverHandlerReturn = ReturnType< 13 | Parameters[0] 14 | >; 15 | 16 | export class HoverProvider { 17 | server: Server; 18 | 19 | constructor(server: Server) { 20 | this.server = server; 21 | 22 | this.server.connection.onHover(this.onHover.bind(this)); 23 | } 24 | 25 | async onHover(params: HoverParams) { 26 | const uri = params.textDocument.uri; 27 | const document = this.server.documentCache.getDocument(uri); 28 | 29 | if (!document) { 30 | return; 31 | } 32 | 33 | const cst = await document.cst(); 34 | const cursorNode = findNodeByPosition(cst.rootNode, params.position); 35 | 36 | if (!cursorNode) { 37 | return; 38 | } 39 | 40 | let result; 41 | let hovers = [globalVariables, localVariables, functions, filters, forLoop]; 42 | 43 | for (const fn of hovers) { 44 | if ((result = fn(cursorNode))) { 45 | break; 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /packages/language-server/src/hovers/local-variables.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | import { onHoverHandlerReturn } from './hover-provider'; 3 | import { bottomTopCursorIterator } from '../utils/bottom-top-cursor-iterator'; 4 | 5 | export function localVariables(cursorNode: SyntaxNode): onHoverHandlerReturn { 6 | if (cursorNode.type !== 'variable') { 7 | return; 8 | } 9 | 10 | for (let node of bottomTopCursorIterator(cursorNode)) { 11 | if (node.type === 'set') { 12 | let cursor = node.walk(); 13 | 14 | cursor.gotoFirstChild(); 15 | 16 | const keys = []; 17 | const values = []; 18 | 19 | while (cursor.gotoNextSibling()) { 20 | if (cursor.currentFieldName() === 'variable') { 21 | keys.push(cursor.nodeText); 22 | } else if (cursor.currentFieldName() === 'value') { 23 | values.push(cursor.nodeText); 24 | } 25 | } 26 | 27 | for (let i = 0; i < keys.length; i++) { 28 | if (keys[i] === cursorNode.text) { 29 | return { 30 | contents: values[i], 31 | }; 32 | } 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /packages/language-server/src/index.ts: -------------------------------------------------------------------------------- 1 | import { createConnection, ProposedFeatures } from 'vscode-languageserver/node'; 2 | import { Server } from './server'; 3 | 4 | const connection = createConnection(ProposedFeatures.all); 5 | 6 | new Server(connection); 7 | 8 | connection.listen(); 9 | -------------------------------------------------------------------------------- /packages/language-server/src/semantic-tokens/semantic-tokens-provider.ts: -------------------------------------------------------------------------------- 1 | import { 2 | SemanticTokensParams, 3 | SemanticTokens, 4 | SemanticTokensBuilder, 5 | } from 'vscode-languageserver'; 6 | import { Server } from '../server'; 7 | import { PreOrderCursorIterator } from '../utils/pre-order-cursor-iterator'; 8 | import { pointToPosition } from '../utils/point-to-position'; 9 | import { semanticTokensLegend } from './tokens-provider'; 10 | import { TreeCursor } from 'web-tree-sitter'; 11 | 12 | const tokenTypes = new Map( 13 | semanticTokensLegend.tokenTypes.map((v, i) => [v, i]) 14 | ); 15 | 16 | const functionTokenType = tokenTypes.get('function')!; 17 | const commentTokenType = tokenTypes.get('comment')!; 18 | 19 | const resolveTokenType = (node: TreeCursor) => { 20 | if ( 21 | node.nodeType === 'property' && 22 | node.currentNode().parent!.nextSibling?.type === 'arguments' 23 | ) { 24 | return functionTokenType; 25 | } 26 | 27 | if (node.nodeType === 'inline_comment') { 28 | return commentTokenType; 29 | } 30 | 31 | return tokenTypes.get(node.nodeType); 32 | }; 33 | 34 | export class SemanticTokensProvider { 35 | server: Server; 36 | 37 | constructor(server: Server) { 38 | this.server = server; 39 | 40 | this.server.connection.languages.semanticTokens.on( 41 | this.serverRequestHandler.bind(this) 42 | ); 43 | } 44 | 45 | async serverRequestHandler(params: SemanticTokensParams) { 46 | const semanticTokens: SemanticTokens = { data: [] }; 47 | const uri = params.textDocument.uri; 48 | const document = this.server.documentCache.getDocument(uri); 49 | 50 | if (!document) { 51 | return semanticTokens; 52 | } 53 | 54 | const cst = await document.cst(); 55 | const tokensBuilder = new SemanticTokensBuilder(); 56 | const nodes = new PreOrderCursorIterator(cst.walk()); 57 | 58 | for (const node of nodes) { 59 | const tokenType = resolveTokenType(node); 60 | 61 | if (tokenType === undefined) { 62 | continue; 63 | } 64 | 65 | const start = pointToPosition(node.startPosition); 66 | const lines = node.nodeText.split('\n'); 67 | let lineNumber = start.line; 68 | let charNumber = start.character; 69 | 70 | for (const line of lines) { 71 | tokensBuilder.push(lineNumber++, charNumber, line.length, tokenType, 0); 72 | 73 | charNumber = 0; 74 | } 75 | } 76 | 77 | return tokensBuilder.build(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /packages/language-server/src/semantic-tokens/tokens-provider.ts: -------------------------------------------------------------------------------- 1 | import { SemanticTokensLegend } from 'vscode-languageserver'; 2 | 3 | export const semanticTokensLegend: SemanticTokensLegend = { 4 | tokenTypes: [ 5 | 'parameter', 6 | 'variable', 7 | 'property', 8 | 'function', 9 | 'method', 10 | 'keyword', 11 | 'comment', 12 | 'string', 13 | 'number', 14 | 'operator', 15 | 'embedded_begin', 16 | 'embedded_end', 17 | 'null', 18 | 'boolean', 19 | ], 20 | tokenModifiers: [], 21 | }; 22 | -------------------------------------------------------------------------------- /packages/language-server/src/server.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ClientCapabilities, 3 | Connection, 4 | InitializeParams, 5 | ServerCapabilities, 6 | TextDocuments, 7 | WorkspaceFolder, 8 | } from 'vscode-languageserver'; 9 | import { TextDocument } from 'vscode-languageserver-textdocument'; 10 | import { validateTwigDocument } from './utils/validate-twig-document'; 11 | import { DocumentCache } from './document-cache'; 12 | import { HoverProvider } from './hovers/hover-provider'; 13 | import { CompletionProvider } from './completions/completion-provider'; 14 | import { SignatureHelpProvider } from './signature-helps/signature-help-provider'; 15 | import { semanticTokensLegend } from './semantic-tokens/tokens-provider'; 16 | import { SemanticTokensProvider } from './semantic-tokens/semantic-tokens-provider'; 17 | import { ConfigurationManager } from './configuration/configuration-manager'; 18 | import { DefinitionProvider } from './definitions/definition-provider'; 19 | 20 | export class Server { 21 | connection: Connection; 22 | documents: TextDocuments; 23 | documentCache!: DocumentCache; 24 | workspaceFolder!: WorkspaceFolder; 25 | 26 | definitionProvider: DefinitionProvider; 27 | 28 | clientCapabilities!: ClientCapabilities; 29 | 30 | constructor(connection: Connection) { 31 | this.connection = connection; 32 | this.documents = new TextDocuments(TextDocument); 33 | 34 | new HoverProvider(this); 35 | new CompletionProvider(this); 36 | new SignatureHelpProvider(this); 37 | new SemanticTokensProvider(this); 38 | this.definitionProvider = new DefinitionProvider(this); 39 | 40 | // Bindings 41 | connection.onInitialize((initializeParams: InitializeParams) => { 42 | this.workspaceFolder = initializeParams.workspaceFolders![0]; 43 | this.documentCache = new DocumentCache(this.workspaceFolder); 44 | 45 | this.clientCapabilities = initializeParams.capabilities; 46 | 47 | const capabilities: ServerCapabilities = { 48 | hoverProvider: true, 49 | definitionProvider: true, 50 | completionProvider: { 51 | resolveProvider: true, 52 | triggerCharacters: ['"', "'", '|', '.', '{'], 53 | }, 54 | signatureHelpProvider: { 55 | triggerCharacters: ['(', ','], 56 | }, 57 | semanticTokensProvider: { 58 | legend: semanticTokensLegend, 59 | full: true, 60 | }, 61 | }; 62 | 63 | return { capabilities }; 64 | }); 65 | 66 | this.connection.onInitialized(async () => { 67 | if (this.clientCapabilities.workspace?.didChangeConfiguration) { 68 | new ConfigurationManager(this); 69 | } 70 | }); 71 | 72 | this.documents.onDidChangeContent((change) => { 73 | validateTwigDocument(change.document, connection); 74 | 75 | // Update text in documentCache 76 | this.documentCache 77 | .getDocument(change.document.uri) 78 | ?.setText(change.document.getText()); 79 | }); 80 | 81 | this.documents.listen(connection); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /packages/language-server/src/signature-helps/signature-help-provider.ts: -------------------------------------------------------------------------------- 1 | import { SignatureHelp, SignatureHelpParams } from 'vscode-languageserver'; 2 | import { Server } from '../server'; 3 | import { findNodeByPosition } from '../utils/find-element-by-position'; 4 | import type { SyntaxNode } from 'web-tree-sitter'; 5 | import { twigFunctionsSignatureInformation } from '../common'; 6 | 7 | export class SignatureHelpProvider { 8 | server: Server; 9 | 10 | constructor(server: Server) { 11 | this.server = server; 12 | 13 | this.server.connection.onSignatureHelp( 14 | this.provideSignatureHelp.bind(this) 15 | ); 16 | } 17 | 18 | async provideSignatureHelp( 19 | params: SignatureHelpParams 20 | ): Promise { 21 | const uri = params.textDocument.uri; 22 | const document = this.server.documentCache.getDocument(uri); 23 | 24 | if (!document) { 25 | return; 26 | } 27 | 28 | const cst = await document.cst(); 29 | const cursorNode = findNodeByPosition(cst.rootNode, params.position); 30 | 31 | if (!cursorNode) { 32 | return; 33 | } 34 | 35 | const argumentsNode = cursorNode.parent; 36 | 37 | if (argumentsNode?.type !== 'arguments') { 38 | return; 39 | } 40 | 41 | const callExpression = argumentsNode.parent; 42 | 43 | if (!callExpression || callExpression.type !== 'call_expression') { 44 | return; 45 | } 46 | 47 | const callName = callExpression.childForFieldName('name')?.text; 48 | 49 | if (!callName) { 50 | return; 51 | } 52 | 53 | const signatureInformation = 54 | twigFunctionsSignatureInformation.get(callName); 55 | 56 | if (!signatureInformation) { 57 | return; 58 | } 59 | 60 | let activeParameter = 0; 61 | 62 | if (signatureInformation.parameters?.length) { 63 | let node: SyntaxNode | null = argumentsNode.firstChild; 64 | 65 | while (node) { 66 | if (node.text === ',') { 67 | activeParameter++; 68 | } 69 | 70 | if (node.equals(cursorNode)) { 71 | break; 72 | } 73 | 74 | node = node.nextSibling; 75 | } 76 | } 77 | 78 | return { 79 | signatures: [signatureInformation], 80 | activeParameter, 81 | }; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/bottom-top-cursor-iterator.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | 3 | export function* bottomTopCursorIterator(startNode: SyntaxNode) { 4 | let node: SyntaxNode | null = startNode; 5 | 6 | while (node) { 7 | yield node; 8 | 9 | node = node.previousNamedSibling ?? node.parent; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/compare-positions.ts: -------------------------------------------------------------------------------- 1 | import { Position } from 'vscode-languageserver/node'; 2 | 3 | export function comparePositions(a: Position, b: Position): number { 4 | if (a.line < b.line) return -1; 5 | if (a.line > b.line) return 1; 6 | 7 | if (a.character < b.character) return -1; 8 | if (a.character > b.character) return 1; 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/docker/command.ts: -------------------------------------------------------------------------------- 1 | export type DockerComposeCommandPart = 'docker-compose' | 'docker compose'; 2 | 3 | type DockerComposeExecParsed = { 4 | dockerComposeCommandPart: DockerComposeCommandPart; 5 | service: TService; 6 | }; 7 | 8 | export type DockerComposeExecCommand = `${DockerComposeCommandPart} exec ${TService} ${string}`; 9 | 10 | /** Parses docker compose command. 11 | * @example 'docker compose exec php bin/console' => { command: 'docker compose', service: 'php' } 12 | */ 13 | export function parseDockerComposeExecCommand( 14 | cmd: DockerComposeExecCommand, 15 | ): DockerComposeExecParsed | undefined { 16 | const dockerComposeRegex = 17 | /(?docker(?:\s+|-)compose)\s+exec\s+((?:-\S+\s+)*)(?\S+)/; 18 | 19 | const match = cmd.match(dockerComposeRegex); 20 | 21 | if (!match) { 22 | return undefined; 23 | } 24 | 25 | const { command, service } = match.groups!; 26 | 27 | return { 28 | dockerComposeCommandPart: command as DockerComposeCommandPart, 29 | service: service as TService, 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/docker/config.ts: -------------------------------------------------------------------------------- 1 | import { exec } from '../exec'; 2 | import { DockerComposeCommandPart } from './command'; 3 | 4 | export type DockerComposeVolume = { 5 | source: string; 6 | target: string; 7 | }; 8 | 9 | type DockerComposeServiceConfig = { 10 | volumes: (DockerComposeVolume & { type: 'bind' | 'volume' | 'tmpfs' })[]; 11 | }; 12 | 13 | export async function getVolumeBindingsForService(dockerComposeCommand: DockerComposeCommandPart, serviceName: string): Promise { 14 | const { stdout, stderr } = await exec(`${dockerComposeCommand} config --format json`).catch((err) => err); 15 | 16 | if (stderr) { 17 | return []; 18 | } 19 | 20 | const services: Record = JSON.parse(stdout).services; 21 | const bindings = services[serviceName].volumes 22 | .filter(v => v.type === 'bind') 23 | .map(({ source, target }) => ({ source, target })); 24 | 25 | return bindings; 26 | } 27 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/document-uri-to-fs-path.ts: -------------------------------------------------------------------------------- 1 | import { DocumentUri } from 'vscode-languageserver'; 2 | import { URI } from 'vscode-uri'; 3 | 4 | export function documentUriToFsPath(documentUri: DocumentUri): string { 5 | return URI.parse(documentUri).fsPath; 6 | } 7 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/exec.ts: -------------------------------------------------------------------------------- 1 | import { promisify } from 'node:util'; 2 | 3 | export const exec: (cmd: string) => Promise<{ stdout: string; stderr: string }> = promisify(require('node:child_process').exec); 4 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/files/fileStat.ts: -------------------------------------------------------------------------------- 1 | import { Stats } from 'fs'; 2 | import { stat } from 'fs/promises'; 3 | 4 | export const fileStat = (fsPath: string): Promise => stat(fsPath).catch(() => null); 5 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/find-element-by-position.ts: -------------------------------------------------------------------------------- 1 | import { Position, Range } from 'vscode-languageserver'; 2 | import { SyntaxNode } from 'web-tree-sitter'; 3 | import { rangeContainsPosition } from './range-contains-position'; 4 | import { pointToPosition } from './point-to-position'; 5 | import { isEmptyEmbedded } from './is-empty-embedded'; 6 | import { comparePositions } from './compare-positions'; 7 | 8 | export function findNodeByPosition( 9 | node: SyntaxNode, 10 | position: Position, 11 | ): SyntaxNode | undefined { 12 | const range = Range.create( 13 | pointToPosition(node.startPosition), 14 | pointToPosition(node.endPosition) 15 | ); 16 | 17 | if (!rangeContainsPosition(range, position)) { 18 | // Cursor inside of empty embedded: {{ | }} 19 | if (isEmptyEmbedded(node)) { 20 | const rangeInsideEmptyEmbedded = Range.create( 21 | pointToPosition(node.endPosition), 22 | pointToPosition(node.nextSibling!.startPosition) 23 | ); 24 | 25 | if (rangeContainsPosition(rangeInsideEmptyEmbedded, position)) { 26 | return node; 27 | } 28 | } 29 | 30 | return; 31 | } 32 | 33 | if (!node.childCount) { 34 | return node; 35 | } 36 | 37 | // Cursor right after embedded_begin: {{| }} 38 | if (isEmptyEmbedded(node) && comparePositions(pointToPosition(node.endPosition), position) === 0) { 39 | return node; 40 | } 41 | 42 | for (const child of node.children) { 43 | const foundNode = findNodeByPosition(child, position); 44 | 45 | if (foundNode) { 46 | return foundNode; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/find-parent-by-type.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | 3 | export function findParentByType( 4 | cursorNode: SyntaxNode, 5 | type: string 6 | ): SyntaxNode | undefined { 7 | let node = cursorNode; 8 | 9 | while (node.parent) { 10 | if (node.type === type) { 11 | return node; 12 | } 13 | node = node.parent; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/fs-path-to-document-uri.ts: -------------------------------------------------------------------------------- 1 | import { DocumentUri } from 'vscode-languageserver'; 2 | import { URI } from 'vscode-uri'; 3 | 4 | export function fsPathToDocumentUri(faPath: string): DocumentUri { 5 | return URI.file(faPath).toString(); 6 | } 7 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/is-empty-embedded.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | 3 | export const isEmptyEmbedded = (node: SyntaxNode) => node.type === 'ERROR' 4 | && node.childCount === 1 5 | && node.firstChild!.type === 'embedded_begin'; 6 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/node/getStringNodeValue.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | 3 | export function getStringNodeValue(stringNode: SyntaxNode) { 4 | if (stringNode.type !== 'string') { 5 | throw new Error('Node is not a string. ' + stringNode.type); 6 | } 7 | 8 | return stringNode.text.slice('"'.length, -'"'.length) 9 | } 10 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/node/index.ts: -------------------------------------------------------------------------------- 1 | export { getStringNodeValue } from './getStringNodeValue'; 2 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/parse-twig.ts: -------------------------------------------------------------------------------- 1 | import { readFile } from 'fs/promises'; 2 | import { join } from 'path'; 3 | import Parser from 'web-tree-sitter'; 4 | 5 | let parser: Parser; 6 | 7 | export async function parseTwig(content: string): Promise { 8 | if (!parser) { 9 | const wasmPath = require.resolve( 10 | join('tree-sitter-twig', 'tree-sitter-twig.wasm') 11 | ); 12 | 13 | await Parser.init(); 14 | parser = new Parser(); 15 | parser.setLanguage(await Parser.Language.load(await readFile(wasmPath))); 16 | } 17 | 18 | return parser.parse(content); 19 | } 20 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/point-to-position.ts: -------------------------------------------------------------------------------- 1 | import { Position } from 'vscode-languageserver/node'; 2 | import { Point } from 'web-tree-sitter'; 3 | 4 | export function pointToPosition(point: Point): Position { 5 | return Position.create(point.row, point.column); 6 | } 7 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/positions-to-range.ts: -------------------------------------------------------------------------------- 1 | import { Position, Range } from 'vscode-languageserver/node'; 2 | 3 | export function positionsToRange(a: Position, b: Position): Range { 4 | return Range.create(a, b) 5 | } 6 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/pre-order-cursor-iterator.ts: -------------------------------------------------------------------------------- 1 | import { TreeCursor } from 'web-tree-sitter'; 2 | 3 | export class PreOrderCursorIterator { 4 | protected cursor; 5 | 6 | constructor(cursor: TreeCursor) { 7 | this.cursor = cursor; 8 | } 9 | 10 | public *[Symbol.iterator](): Generator { 11 | const constructor = this.constructor as any; 12 | 13 | yield this.cursor; 14 | 15 | if (this.cursor.gotoFirstChild()) { 16 | yield* new constructor(this.cursor); 17 | 18 | while (this.cursor.gotoNextSibling()) { 19 | yield* new constructor(this.cursor); 20 | } 21 | 22 | this.cursor.gotoParent(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/range-contains-position.ts: -------------------------------------------------------------------------------- 1 | import { Position, Range } from 'vscode-languageserver/node'; 2 | import { comparePositions } from './compare-positions'; 3 | 4 | export function rangeContainsPosition( 5 | range: Range, 6 | position: Position 7 | ): boolean { 8 | return ( 9 | comparePositions(position, range.start) >= 0 && 10 | comparePositions(position, range.end) <= 0 11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/read-dir.ts: -------------------------------------------------------------------------------- 1 | import { readdir } from 'fs/promises'; 2 | import { join } from 'path'; 3 | 4 | export default async function* readDir(dir: string): AsyncGenerator { 5 | for (const entry of await readdir(dir, { withFileTypes: true })) { 6 | const childPath = join(dir, entry.name); 7 | 8 | if (entry.isDirectory()) { 9 | yield* readDir(childPath); 10 | } else { 11 | yield childPath; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/symfony/twigConfig.ts: -------------------------------------------------------------------------------- 1 | import { DockerComposeExecCommand, parseDockerComposeExecCommand } from '../../utils/docker/command'; 2 | import { getVolumeBindingsForService } from '../../utils/docker/config'; 3 | import { exec } from '../../utils/exec'; 4 | 5 | type TwigConfig = { 6 | default_path: string; 7 | paths: Record; 8 | }; 9 | 10 | type TemplateNamespace = `@${string}` | ''; 11 | 12 | export type TemplatePathMapping = { 13 | directory: string; 14 | namespace: TemplateNamespace; 15 | }; 16 | 17 | const aliasToNamespace = (alias: string): TemplateNamespace => { 18 | return alias === null ? '' : `@${alias}`; 19 | }; 20 | 21 | export async function getTemplatePathMappingsFromSymfony(phpBinConsoleCommand: string): Promise { 22 | const command = phpBinConsoleCommand + ' debug:config twig --format json'; 23 | const { stdout, stderr } = await exec(command).catch((err) => err); 24 | 25 | if (stderr && !stdout) { 26 | console.error(command); 27 | return []; 28 | } 29 | 30 | const json = JSON.parse(stdout); 31 | const twigConfig: TwigConfig = json.twig; 32 | 33 | const dockerComposeCommandParsed = parseDockerComposeExecCommand(phpBinConsoleCommand as DockerComposeExecCommand); 34 | 35 | if (!dockerComposeCommandParsed) { 36 | // Paths in twig config are real and point to the user's fs. 37 | const mappings = Object.entries(twigConfig.paths).map( 38 | ([directory, alias]): TemplatePathMapping => ({ 39 | directory, 40 | namespace: aliasToNamespace(alias), 41 | }), 42 | ); 43 | 44 | return [...mappings, { directory: twigConfig.default_path, namespace: '' }]; 45 | } 46 | 47 | // Paths in twig config are bound to the user's fs via docker compose volumes. 48 | // We need to convert them into real paths. 49 | 50 | const { dockerComposeCommandPart, service } = dockerComposeCommandParsed; 51 | const bindings = await getVolumeBindingsForService(dockerComposeCommandPart, service); 52 | 53 | const convertAllBindings = (path: string) => { 54 | return bindings.reduce((path, { source, target }) => path.replace(target, source), path); 55 | }; 56 | 57 | const mappings = Object.entries(twigConfig.paths).map( 58 | ([directory, alias]): TemplatePathMapping => ({ 59 | directory: convertAllBindings(directory), 60 | namespace: aliasToNamespace(alias), 61 | }), 62 | ); 63 | 64 | return [...mappings, { directory: convertAllBindings(twigConfig.default_path), namespace: '' }]; 65 | } 66 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/to-previous-sibling-or-parent-iterator.ts: -------------------------------------------------------------------------------- 1 | import { SyntaxNode } from 'web-tree-sitter'; 2 | 3 | export default async function* toPreviousSiblingOrParentIterator( 4 | node: SyntaxNode 5 | ): AsyncGenerator { 6 | let previousSibling: SyntaxNode | null = node; 7 | 8 | while ((previousSibling = previousSibling.previousSibling)) { 9 | yield previousSibling; 10 | } 11 | 12 | if (node.parent) { 13 | yield* toPreviousSiblingOrParentIterator(node.parent); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/trim-twig-extension.ts: -------------------------------------------------------------------------------- 1 | const reTwigExtension = /\.twig$/i; 2 | 3 | export function trimTwigExtension(path: string): string { 4 | return path.replace(reTwigExtension, ''); 5 | } 6 | -------------------------------------------------------------------------------- /packages/language-server/src/utils/validate-twig-document.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Connection, 3 | Diagnostic, 4 | DiagnosticSeverity, 5 | } from 'vscode-languageserver'; 6 | import { TextDocument } from 'vscode-languageserver-textdocument'; 7 | import { parseTwig } from './parse-twig'; 8 | import { PreOrderCursorIterator } from './pre-order-cursor-iterator'; 9 | import { pointToPosition } from './point-to-position'; 10 | 11 | export async function validateTwigDocument( 12 | document: TextDocument, 13 | connection: Connection 14 | ): Promise { 15 | const text = document.getText(); 16 | const diagnostics: Diagnostic[] = []; 17 | const cst = await parseTwig(text); 18 | 19 | if (cst.rootNode.hasError()) { 20 | const cursor = cst.walk(); 21 | const nodes = new PreOrderCursorIterator(cursor); 22 | 23 | for (const node of nodes) { 24 | if (node.nodeType === 'ERROR') { 25 | const diagnostic: Diagnostic = { 26 | severity: DiagnosticSeverity.Warning, 27 | range: { 28 | start: pointToPosition(node.startPosition), 29 | end: pointToPosition(node.endPosition), 30 | }, 31 | message: `Unexpected syntax`, 32 | }; 33 | 34 | diagnostics.push(diagnostic); 35 | } 36 | } 37 | } 38 | 39 | connection.sendDiagnostics({ uri: document.uri, diagnostics }); 40 | } 41 | -------------------------------------------------------------------------------- /packages/language-server/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2020", 4 | "lib": ["es2020"], 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "sourceMap": true, 8 | "strict": true, 9 | "outDir": "out", 10 | "rootDir": "src", 11 | "esModuleInterop": true, 12 | }, 13 | "include": ["src"], 14 | "exclude": ["node_modules"] 15 | } 16 | -------------------------------------------------------------------------------- /packages/language-server/tsconfig.tsbuildinfo: -------------------------------------------------------------------------------- 1 | {"root":["./src/common.ts","./src/document-cache.ts","./src/index.ts","./src/server.ts","./src/completions/completion-provider.ts","./src/completions/filters.ts","./src/completions/for-loop.ts","./src/completions/functions.ts","./src/completions/global-variables.ts","./src/completions/local-variables.ts","./src/completions/template-paths.ts","./src/configuration/configuration-manager.ts","./src/configuration/language-server-settings.ts","./src/constants/template-usage.ts","./src/definitions/definition-provider.ts","./src/hovers/filters.ts","./src/hovers/for-loop.ts","./src/hovers/functions.ts","./src/hovers/global-variables.ts","./src/hovers/hover-provider.ts","./src/hovers/local-variables.ts","./src/semantic-tokens/semantic-tokens-provider.ts","./src/semantic-tokens/tokens-provider.ts","./src/signature-helps/signature-help-provider.ts","./src/utils/bottom-top-cursor-iterator.ts","./src/utils/compare-positions.ts","./src/utils/document-uri-to-fs-path.ts","./src/utils/exec.ts","./src/utils/find-element-by-position.ts","./src/utils/find-parent-by-type.ts","./src/utils/fs-path-to-document-uri.ts","./src/utils/is-empty-embedded.ts","./src/utils/parse-twig.ts","./src/utils/point-to-position.ts","./src/utils/positions-to-range.ts","./src/utils/pre-order-cursor-iterator.ts","./src/utils/range-contains-position.ts","./src/utils/read-dir.ts","./src/utils/to-previous-sibling-or-parent-iterator.ts","./src/utils/trim-twig-extension.ts","./src/utils/validate-twig-document.ts","./src/utils/docker/command.ts","./src/utils/docker/config.ts","./src/utils/files/fileStat.ts","./src/utils/node/getStringNodeValue.ts","./src/utils/node/index.ts","./src/utils/symfony/twigConfig.ts"],"version":"5.7.2"} -------------------------------------------------------------------------------- /packages/vscode/.vscodeignore: -------------------------------------------------------------------------------- 1 | # See https://github.com/microsoft/vscode-vsce/issues/580 2 | # External ignore files 3 | ../** 4 | ../../** 5 | 6 | # Local ingore files 7 | src 8 | .vscodeignore 9 | package-lock.json 10 | tsconfig.json 11 | -------------------------------------------------------------------------------- /packages/vscode/LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /packages/vscode/README.md: -------------------------------------------------------------------------------- 1 | # VSCode Twig extension 2 | 3 | ## Download 4 | 5 | You can install this extension from VSCode Marketplace - [Modern Twig](https://marketplace.visualstudio.com/items?itemName=Stanislav.vscode-twig) 6 | 7 | ## Features 8 | - Syntax highlighting 9 | - Diagnostics 10 | - Completion 11 | - Hover 12 | - Signature Help 13 | 14 | ### Syntax highlighting 15 | ![1](https://github.com/kaermorchen/twig-language-server/assets/11972062/c295475f-844e-4748-90de-35c98554f6f4) 16 | 17 | ### Diagnostics 18 | ![2](https://github.com/kaermorchen/twig-language-server/assets/11972062/7e3b3d4b-e8a6-4cc9-acd6-b73552d008e6) 19 | 20 | ### Completion and Signature Help 21 | ![3](https://github.com/kaermorchen/twig-language-server/assets/11972062/4d2701c8-9208-45ee-ae45-6126330d4131) 22 | 23 | ### Hover 24 | ![2](https://github.com/kaermorchen/twig-language-server/assets/11972062/fbb75606-a487-4b55-9db3-c15b97bb8a9a) 25 | 26 | ## Note 27 | It uses [Twig Language Server](https://github.com/kaermorchen/twig-language-server/tree/master/packages/language-server) under the hood. 28 | -------------------------------------------------------------------------------- /packages/vscode/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaermorchen/twig-language-server/6c766d9f49c5b05ac36d11f74527c82e009be884/packages/vscode/assets/logo.png -------------------------------------------------------------------------------- /packages/vscode/languages/twig.configuration.json: -------------------------------------------------------------------------------- 1 | { 2 | "comments": { 3 | "blockComment": ["{#", "#}"] 4 | }, 5 | "surroundingPairs": [ 6 | { "open": "'", "close": "'" }, 7 | { "open": "\"", "close": "\"" }, 8 | { "open": "{", "close": "}" }, 9 | { "open": "[", "close": "]" }, 10 | { "open": "(", "close": ")" }, 11 | { "open": "<", "close": ">" } 12 | ], 13 | "autoClosingPairs": [ 14 | { "open": "'", "close": "'" }, 15 | { "open": "\"", "close": "\"" }, 16 | { "open": "{", "close": "}" }, 17 | { "open": "[", "close": "]" }, 18 | { "open": "(", "close": ")" }, 19 | { "open": "<", "close": ">" } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /packages/vscode/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vscode-twig", 3 | "displayName": "Modern Twig", 4 | "description": "A Twig extension for VS Code", 5 | "author": "Stanislav Romanov ", 6 | "license": "Mozilla Public License 2.0", 7 | "version": "0.7.0", 8 | "engines": { 9 | "vscode": "^1.74.0" 10 | }, 11 | "activationEvents": [ 12 | "onStartupFinished" 13 | ], 14 | "main": "./out/extension.js", 15 | "publisher": "stanislav", 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/kaermorchen/twig-language-server", 19 | "directory": "packages/vscode" 20 | }, 21 | "files": [ 22 | "out/", 23 | "LICENSE", 24 | "README.md" 25 | ], 26 | "keywords": [ 27 | "Twig" 28 | ], 29 | "categories": [ 30 | "Programming Languages", 31 | "Linters" 32 | ], 33 | "icon": "assets/logo.png", 34 | "scripts": { 35 | "vscode:prepublish": "tsc --build" 36 | }, 37 | "contributes": { 38 | "configuration": { 39 | "title": "Modern Twig", 40 | "properties": { 41 | "modernTwig.phpBinConsoleCommand": { 42 | "type": "string", 43 | "markdownDescription": "Shell command that will be used for PHP command execution. \n\ne.g. `php bin/console` \n\nSee: https://symfony.com/doc/current/templates.html#inspecting-twig-information" 44 | } 45 | } 46 | }, 47 | "languages": [ 48 | { 49 | "id": "twig", 50 | "aliases": [ 51 | "HTML (Twig)", 52 | "twig" 53 | ], 54 | "extensions": [ 55 | ".twig", 56 | ".html.twig" 57 | ], 58 | "configuration": "./languages/twig.configuration.json" 59 | } 60 | ], 61 | "grammars": [ 62 | { 63 | "language": "twig", 64 | "scopeName": "text.html.twig", 65 | "path": "./syntaxes/html.tmLanguage.json", 66 | "embeddedLanguages": { 67 | "text.html": "html", 68 | "source.twig": "twig", 69 | "source.js": "javascript", 70 | "source.json": "json", 71 | "source.css": "css" 72 | } 73 | } 74 | ], 75 | "semanticTokenTypes": [ 76 | { 77 | "id": "embedded_begin", 78 | "superType": "embedded_delimiter", 79 | "description": "Begin of embedded" 80 | }, 81 | { 82 | "id": "embedded_end", 83 | "superType": "embedded_delimiter", 84 | "description": "End of embedded" 85 | }, 86 | { 87 | "id": "null", 88 | "superType": "constant", 89 | "description": "null or none" 90 | }, 91 | { 92 | "id": "boolean", 93 | "superType": "constant", 94 | "description": "true or false" 95 | } 96 | ], 97 | "configurationDefaults": { 98 | "editor.semanticTokenColorCustomizations": { 99 | "enabled": true, 100 | "rules": { 101 | "embedded_delimiter": { 102 | "foreground": "#9AA83A" 103 | }, 104 | "constant": { 105 | "foreground": "#D16969" 106 | } 107 | } 108 | } 109 | } 110 | }, 111 | "devDependencies": { 112 | "@types/node": "^20.2.6", 113 | "@types/vscode": "^1.74.0", 114 | "typescript": "^5.1.3" 115 | }, 116 | "dependencies": { 117 | "twig-language-server": "^0.7.0", 118 | "vscode-languageclient": "^8.1.0" 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /packages/vscode/src/extension.ts: -------------------------------------------------------------------------------- 1 | import { 2 | workspace, 3 | ExtensionContext, 4 | window, 5 | WorkspaceFolder, 6 | RelativePattern, 7 | } from 'vscode'; 8 | import { 9 | LanguageClient, 10 | LanguageClientOptions, 11 | ServerOptions, 12 | TransportKind, 13 | } from 'vscode-languageclient/node'; 14 | 15 | const outputChannel = window.createOutputChannel('Twig Language Server'); 16 | const clients = new Map(); 17 | 18 | export function activate(context: ExtensionContext) { 19 | workspace.workspaceFolders?.forEach((folder) => 20 | addWorkspaceFolder(folder, context) 21 | ); 22 | 23 | workspace.onDidChangeWorkspaceFolders(({ added, removed }) => { 24 | added.forEach((folder) => addWorkspaceFolder(folder, context)); 25 | removed.forEach((folder) => removeWorkspaceFolder(folder)); 26 | }); 27 | } 28 | 29 | export async function deactivate(): Promise { 30 | for (const client of clients.values()) { 31 | await client.stop(); 32 | } 33 | } 34 | 35 | async function addWorkspaceFolder( 36 | workspaceFolder: WorkspaceFolder, 37 | context: ExtensionContext 38 | ): Promise { 39 | const folderPath = workspaceFolder.uri.fsPath; 40 | const fileEvents = workspace.createFileSystemWatcher( 41 | new RelativePattern(workspaceFolder, '*.twig') 42 | ); 43 | 44 | context.subscriptions.push(fileEvents); 45 | 46 | if (clients.has(folderPath)) { 47 | return; 48 | } 49 | 50 | const module = require.resolve('twig-language-server'); 51 | const serverOptions: ServerOptions = { 52 | run: { module, transport: TransportKind.ipc }, 53 | debug: { 54 | module, 55 | transport: TransportKind.ipc, 56 | options: { execArgv: ['--nolazy', `--inspect=6009`] }, 57 | }, 58 | }; 59 | 60 | const clientOptions: LanguageClientOptions = { 61 | workspaceFolder, 62 | outputChannel, 63 | documentSelector: [ 64 | { 65 | scheme: 'file', 66 | language: 'twig', 67 | pattern: `${folderPath}/**`, 68 | }, 69 | ], 70 | synchronize: { fileEvents }, 71 | }; 72 | 73 | const client = new LanguageClient( 74 | 'twig-language-server', 75 | 'Twig Language Server', 76 | serverOptions, 77 | clientOptions 78 | ); 79 | 80 | clients.set(folderPath, client); 81 | 82 | await client.start(); 83 | } 84 | 85 | async function removeWorkspaceFolder( 86 | workspaceFolder: WorkspaceFolder 87 | ): Promise { 88 | const folderPath = workspaceFolder.uri.fsPath; 89 | const client = clients.get(folderPath); 90 | 91 | if (client) { 92 | clients.delete(folderPath); 93 | 94 | await client.stop(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /packages/vscode/syntaxes/html.tmLanguage.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twig", 3 | "scopeName": "text.html.twig", 4 | "injections": { 5 | "text.html.twig - (meta.embedded | meta.tag), L:((text.html.twig meta.tag) - meta.embedded.block.twig), L:(source.js - meta.embedded.block.twig), L:(source.css - meta.embedded.block.twig)": { 6 | "patterns": [ 7 | { 8 | "include": "#twig-tag" 9 | } 10 | ] 11 | } 12 | }, 13 | "patterns": [ 14 | { 15 | "include": "text.html.derivative" 16 | } 17 | ], 18 | "repository": { 19 | "twig-tag": { 20 | "patterns": [ 21 | { 22 | "begin": "\\{(\\{|\\%|\\#)", 23 | "beginCaptures": { 24 | "0": { 25 | "name": "punctuation.section.embedded.begin.twig" 26 | } 27 | }, 28 | "end": "(\\}|\\%|\\#)\\}", 29 | "endCaptures": { 30 | "0": { 31 | "name": "punctuation.section.embedded.end.twig" 32 | } 33 | }, 34 | "name": "meta.embedded.block.twig", 35 | "contentName": "source.twig", 36 | "patterns": [ 37 | { 38 | "include": "source.twig" 39 | } 40 | ] 41 | } 42 | ] 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /packages/vscode/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "ES2020", 5 | "outDir": "out", 6 | "lib": [ 7 | "ES2020" 8 | ], 9 | "sourceMap": true, 10 | "rootDir": "src", 11 | "strict": true 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /packages/vscode/tsconfig.tsbuildinfo: -------------------------------------------------------------------------------- 1 | {"root":["./src/extension.ts"],"version":"5.7.2"} -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "references": [ 3 | { 4 | "path": "packages/language-server" 5 | }, 6 | { 7 | "path": "packages/vscode" 8 | } 9 | ], 10 | "files": [] 11 | } 12 | --------------------------------------------------------------------------------