├── .github └── workflows │ ├── release.yml │ └── tests.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── djlsp ├── __init__.py ├── __main__.py ├── cli.py ├── constants.py ├── index.py ├── parser.py ├── scripts │ └── django-collector.py └── server.py ├── pyproject.toml ├── releasing.md ├── setup.cfg ├── tests ├── __init__.py ├── django_test │ ├── .helix │ │ └── languages.toml │ ├── django_app │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── static │ │ │ └── django_app.js │ │ ├── templates │ │ │ └── django_app.html │ │ ├── templatetags │ │ │ ├── __init__.py │ │ │ └── django_app.py │ │ └── urls.py │ ├── django_test │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── test-static-folder │ │ └── .gitkeep ├── test_completion_kinds.py ├── test_django_collector.py └── test_parser.py ├── tox.ini └── vscode ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .vscodeignore ├── README.md ├── RELEASE.md ├── client ├── package-lock.json ├── package.json ├── src │ └── extension.ts └── tsconfig.json ├── icon.png ├── package-lock.json ├── package.json └── tsconfig.json /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release.yml 2 | on: 3 | push: 4 | tags: 5 | - '*' 6 | 7 | jobs: 8 | tests: 9 | name: tests 10 | uses: ./.github/workflows/tests.yml 11 | 12 | build: 13 | name: Build distribution 14 | runs-on: ubuntu-latest 15 | needs: tests 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v4 19 | - name: Set up Python 20 | uses: actions/setup-python@v5 21 | with: 22 | python-version: "3.x" 23 | - name: Install dependencies 24 | run: make install-ci 25 | - name: Build package 26 | run: make build 27 | - name: Store the distribution packages 28 | uses: actions/upload-artifact@v4 29 | with: 30 | name: packages-${{ github.ref_name }} 31 | path: dist/* 32 | 33 | release: 34 | name: Release to PyPI 35 | needs: build 36 | runs-on: ubuntu-latest 37 | environment: 38 | name: pypi 39 | url: https://pypi.org/project/${{ github.repository }} 40 | permissions: 41 | id-token: write 42 | steps: 43 | - name: Download artifacts 44 | uses: actions/download-artifact@v4 45 | with: 46 | name: packages-${{ github.ref_name }} 47 | path: dist/ 48 | - name: Publish package distributions to PyPI 49 | uses: pypa/gh-action-pypi-publish@release/v1 50 | with: 51 | password: ${{ secrets.PYPI_API_TOKEN }} 52 | 53 | github-release: 54 | name: Create release on Github 55 | needs: release 56 | runs-on: ubuntu-latest 57 | steps: 58 | - name: Download artifacts 59 | uses: actions/download-artifact@v4 60 | with: 61 | name: packages-${{ github.ref_name }} 62 | path: dist/ 63 | - name: Create new release 64 | continue-on-error: true 65 | uses: softprops/action-gh-release@v2 66 | with: 67 | token: ${{ secrets.GITHUB_TOKEN }} 68 | body: | 69 | What's changed: 70 | * TODO 71 | 72 | Get it [here](https://pypi.org/project/django-template-lsp/${{ github.ref_name }}) 73 | draft: true 74 | files: dist/ 75 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | workflow_call: 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | python-version: ["3.10", "3.11", "3.12", "3.13"] 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v5 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - name: Install dependencies 20 | run: make develop 21 | - name: Run tests 22 | run: make test 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Static project files 2 | /env/ 3 | /tests/django_test/env/ 4 | 5 | # Test files 6 | /tests/django_test/django_app/templates/test.html 7 | 8 | # Python files 9 | .Python 10 | .python-version 11 | *.pyc 12 | __pycache__ 13 | pip-selfcheck.json 14 | 15 | # Build files 16 | *.egg-info/ 17 | /build/ 18 | /dist/ 19 | 20 | # OS and project files 21 | *sqlite3 22 | *djlsp.log 23 | .DS_Store 24 | .mypy_cache 25 | .template-version 26 | .vscode 27 | .pytest_cache/ 28 | .env 29 | *.swp 30 | .idea/ 31 | /.helix/ 32 | 33 | # Coverage 34 | .coverage 35 | coverage.xml 36 | htmlcov/ 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ENV = env 2 | BIN = $(ENV)/bin 3 | PYTHON = $(BIN)/python 4 | CODE_LOCATIONS = djlsp tests 5 | 6 | clean: 7 | rm -rf $(ENV) 8 | rm -rf build 9 | rm -rf dist 10 | rm -rf *.egg 11 | rm -rf *.egg-info 12 | find | grep -i ".*\.pyc$$" | xargs -r -L1 rm 13 | 14 | $(ENV): 15 | python3 -m venv $(ENV) 16 | $(PYTHON) -m pip install --upgrade pip setuptools wheel twine 17 | $(PYTHON) -m pip install -e .[dev] 18 | 19 | develop: $(ENV) 20 | 21 | fix-codestyle: 22 | $(BIN)/black $(CODE_LOCATIONS) 23 | $(BIN)/isort $(CODE_LOCATIONS) 24 | 25 | lint: 26 | $(BIN)/black --check $(CODE_LOCATIONS) 27 | $(BIN)/isort --check-only $(CODE_LOCATIONS) 28 | $(BIN)/flake8 $(CODE_LOCATIONS) 29 | 30 | test: lint 31 | $(BIN)/tox run 32 | 33 | django-env: 34 | python3 -m venv tests/django_test/env 35 | tests/django_test/env/bin/python -m pip install django~=4.2.0 36 | 37 | helix: $(ENV) django-env 38 | touch tests/django_test/django_app/templates/test.html 39 | . $(ENV)/bin/activate; hx --working-dir tests/django_test tests/django_test/django_app/templates/test.html 40 | 41 | install-ci: $(ENV) 42 | $(PYTHON) -m pip install --upgrade pip setuptools wheel twine build . 43 | 44 | .PHONY: build 45 | build: 46 | $(PYTHON) -m build 47 | $(BIN)/twine check dist/* 48 | 49 | upload: 50 | $(BIN)/twine upload --skip-existing dist/* 51 | 52 | build-vscode-extension: 53 | npm --prefix ./vscode/ run compile 54 | npm --prefix ./vscode/ run vsce-package 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 |

Django Template LSP server

5 | 6 | The Django Template LSP server enhances your Django development 7 | experience with powerful features for navigating and editing template files. 8 | This LSP supports: 9 | 10 | ### Completions 11 | 12 | - **Custom Tags and Filters**: Autocomplete for your custom template tags and filters. 13 | - **Template**: Suggestions for `extends` and `includes` statements. 14 | - **Load Tag**: Autocomplete for `{% load %}` tags. 15 | - **Static Files**: Path suggestions for `{% static %}` tags. 16 | - **URLs**: Autocomplete for `{% url %}` tags. 17 | 18 | ### Go to Definitions 19 | 20 | - **Template**: Jump directly to the templates used in `extends` and `includes`. 21 | - **URL Tag**: Navigate to the views referenced in `{% url %}` tags. 22 | - **Tags and Filters**: Quickly access the definitions of custom tags and filters. 23 | - **Context Variables**: Partial support for jumping to context definitions. 24 | 25 | ### Hover Documentation 26 | 27 | - **URLs**: Inline documentation for `{% url %}` tags. 28 | - **Tags and Filters**: Detailed descriptions for template tags and filters. 29 | 30 | 31 | ## Support (tested) 32 | 33 | - Python: 3.10, 3.11, 3.12, 3.13 34 | - Django: 4.2, 5.0, 5.1, 5.2 35 | 36 | 37 | ## Installation 38 | 39 | To install the package globally and isolate it from other Python environments, use `pipx`: 40 | 41 | ```bash 42 | pipx install django-template-lsp 43 | ``` 44 | 45 | Once installed, the Django template LSP server is accessible via the following commands: 46 | 47 | - `djlsp` 48 | - `django-template-lsp` 49 | 50 | ## Options 51 | 52 | - `env_directories` (list[string]) default (list of relative or absolute paths): ["env", ".env", "venv", ".venv"] 53 | - `docker_compose_file` (string) default: "docker-compose.yml" 54 | - `docker_compose_service` (string) default: "django" 55 | - `django_settings_module` (string) default (auto detected when empty): "" 56 | - `cache` (boolean/string) default (either true/false or a filepath to the cachefile): false 57 | 58 | ## Data Collection Method 59 | 60 | The Django Template LSP Server collects project data by executing a script in the following order: 61 | 62 | 1. **Virtual Environment**: 63 | - Checks for a virtual environment in the root directory within one of these folders: `env`, `.env`, `venv`, or `.venv`. 64 | - If found, runs the `django-collector.py` script using the virtual environment's Python interpreter. 65 | 66 | 2. **Docker Compose**: 67 | - If a Docker Compose file (`docker-compose.yml` by default) is present and includes the specified service (`django` by default), the script is executed within that Docker service. 68 | 69 | 3. **Global Python**: 70 | - If neither a virtual environment nor Docker Compose is detected, the script runs using the global `python3` installation on the system. 71 | 72 | **Note**: The data collection process will fail if there are Python syntax errors or missing imports in your project. 73 | 74 | ## Type hints 75 | 76 | Due to the highly dynamic nature of Python and Django, it can be challenging to 77 | identify the available context data within templates. To address this, basic 78 | type hint support is provided directly in the template files: 79 | 80 | ```html 81 | {# type blog: blogs.models.Blog #} 82 | ``` 83 | 84 | ## Editors 85 | 86 | ### Helix 87 | 88 | In your global or project `languages.toml` add the following 89 | 90 | ```toml 91 | [language-server.djlsp] 92 | command = "djlsp" 93 | 94 | [[language]] 95 | name = "html" 96 | language-servers = [ "vscode-html-language-server", "djlsp" ] 97 | ``` 98 | 99 | Project settings `.helix/languages.toml`: 100 | 101 | ```toml 102 | [language-server.djlsp.config] 103 | django_settings_modules="" 104 | ``` 105 | 106 | ### Neovim 107 | 108 | In your lspconfig add the following 109 | 110 | ```lua 111 | require'lspconfig'.djlsp.setup{ 112 | cmd = { "" }, 113 | init_options = { 114 | django_settings_module = "", 115 | docker_compose_file = "docker-compose.yml", 116 | docker_compose_service = "django" 117 | } 118 | } 119 | ``` 120 | 121 | ### VSCode 122 | 123 | To use the Django template LSP with VSCode read the following [readme](vscode/README.md) 124 | 125 | ## Development 126 | 127 | For local development, using [Helix](https://helix-editor.com) is the easiest approach. 128 | The configuration for using the source Django template language server, with logging enabled, is already set up. 129 | 130 | To start the Helix editor with the environment activated and the correct workspace loaded, run: 131 | 132 | ```bash 133 | make helix 134 | ``` 135 | 136 | ### neovim 137 | 138 | Locally install the package 139 | 140 | ``` sh 141 | make develop 142 | ``` 143 | 144 | Point neovim's `djlsp` to the locally installed copy 145 | 146 | ``` lua 147 | require("lspconfig").djlsp.setup({ 148 | cmd = { "/path/to/django-template-lsp/.venv/bin/djlsp" }, 149 | root_dir = require("lspconfig.util").root_pattern("manage.py", ".git"), 150 | }) 151 | ``` 152 | 153 | If you want to access the log while developing, add the `--enable-log` flag to the cmd. 154 | The logfile will be written to a file in your current working directory named `djlsp.log`. 155 | 156 | ``` lua 157 | require("lspconfig").djlsp.setup({ 158 | cmd = { "/path/to/django-template-lsp/.venv/bin/djlsp", "--enable-log" }, 159 | }) 160 | ``` 161 | -------------------------------------------------------------------------------- /djlsp/__init__.py: -------------------------------------------------------------------------------- 1 | from importlib.metadata import version 2 | 3 | __version__ = version("django-template-lsp") 4 | -------------------------------------------------------------------------------- /djlsp/__main__.py: -------------------------------------------------------------------------------- 1 | from djlsp.cli import main 2 | 3 | main() 4 | -------------------------------------------------------------------------------- /djlsp/cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import logging 3 | import os 4 | 5 | from pygls.protocol import LanguageServerProtocol 6 | from pygls.workspace.workspace import Workspace 7 | 8 | from djlsp import __version__ 9 | from djlsp.server import DjangoTemplateLanguageServer, server 10 | 11 | 12 | def main(): 13 | parser = argparse.ArgumentParser(description="Django template LSP") 14 | parser.add_argument( 15 | "--version", 16 | action="version", 17 | version=f"%(prog)s {__version__}", 18 | ) 19 | parser.add_argument("--enable-log", action="store_true") 20 | parser.add_argument( 21 | "--env-directory", 22 | action="append", 23 | help="Env directory to check, can be relative or absolute path", 24 | ) 25 | parser.add_argument( 26 | "--docker-compose-file", 27 | type=str, 28 | default="docker-compose.yml", 29 | help="Path to the docker-compose.yml file", 30 | ) 31 | parser.add_argument( 32 | "--docker-compose-service", 33 | type=str, 34 | default="django", 35 | help="Docker Compose service name for Django", 36 | ) 37 | parser.add_argument( 38 | "--django-settings-module", 39 | type=str, 40 | default="", 41 | help="Django settings module. If left empty, autodetection will be attempted.", 42 | ) 43 | parser.add_argument( 44 | "--collect", 45 | action="store_true", 46 | help="Attempt to collect Django data and display logs.", 47 | ) 48 | parser.add_argument( 49 | "--cache", 50 | nargs="?", 51 | const=True, 52 | default=False, 53 | help="Use cache for Django data collection (optional provide a filepath)", 54 | ) 55 | 56 | args = parser.parse_args() 57 | 58 | initialization_options = { 59 | "env_directories": args.env_directory, 60 | "docker_compose_file": args.docker_compose_file, 61 | "docker_compose_service": args.docker_compose_service, 62 | "django_settings_module": args.django_settings_module, 63 | "cache": args.cache, 64 | } 65 | 66 | if args.collect: 67 | logger = logging.getLogger("djlsp") 68 | logger.setLevel(logging.DEBUG) 69 | console_handler = logging.StreamHandler() 70 | console_handler.setLevel(logging.DEBUG) 71 | logger.addHandler(console_handler) 72 | 73 | logger.info(f"Workspace path: {os.getcwd()}") 74 | 75 | class MockLanguageServerProtocol(LanguageServerProtocol): 76 | def __init__(self, *args, **kwargs): 77 | super().__init__(*args, **kwargs) 78 | self._workspace = Workspace( 79 | root_uri=f"file://{os.getcwd()}", 80 | ) 81 | 82 | language_server = DjangoTemplateLanguageServer( 83 | "django-template-lsp", __version__, protocol_cls=MockLanguageServerProtocol 84 | ) 85 | language_server.set_initialization_options(initialization_options) 86 | language_server.get_django_data(update_file_watcher=False) 87 | else: 88 | if args.enable_log: 89 | logger = logging.getLogger("djlsp") 90 | logger.setLevel(logging.DEBUG) 91 | file_handler = logging.FileHandler("djlsp.log") 92 | file_handler.setLevel(logging.DEBUG) 93 | logger.addHandler(file_handler) 94 | 95 | server.set_initialization_options(initialization_options) 96 | server.start_io() 97 | -------------------------------------------------------------------------------- /djlsp/constants.py: -------------------------------------------------------------------------------- 1 | BUILTIN = "__builtins__" 2 | 3 | FALLBACK_DJANGO_DATA = { 4 | "file_watcher_globs": ["**/templates/**", "**/templatetags/**", "**/static/**"], 5 | "static_files": [], 6 | "urls": {}, 7 | "libraries": { 8 | "__builtins__": { 9 | "tags": { 10 | "autoescape": {"inner_tags": [], "closing_tag": "endautoescape"}, 11 | "comment": {"inner_tags": [], "closing_tag": "endcomment"}, 12 | "cycle": {}, 13 | "csrf_token": {}, 14 | "debug": {}, 15 | "filter": {"inner_tags": [], "closing_tag": "endfilter"}, 16 | "firstof": {}, 17 | "for": {"inner_tags": ["empty"], "closing_tag": "endfor"}, 18 | "if": {"inner_tags": ["else", "elif"], "closing_tag": "endif"}, 19 | "ifchanged": {"inner_tags": [], "closing_tag": "endifchanged"}, 20 | "load": {}, 21 | "lorem": {}, 22 | "now": {}, 23 | "regroup": {}, 24 | "resetcycle": {}, 25 | "spaceless": {"inner_tags": [], "closing_tag": "endspaceless"}, 26 | "templatetag": {}, 27 | "url": {}, 28 | "verbatim": {"inner_tags": [], "closing_tag": "endverbatim"}, 29 | "widthratio": {}, 30 | "with": {"inner_tags": [], "closing_tag": "endwith"}, 31 | "block": {"inner_tags": [], "closing_tag": "endblock"}, 32 | "extends": {}, 33 | "include": {}, 34 | }, 35 | "filters": { 36 | "addslashes": {}, 37 | "capfirst": {}, 38 | "escapejs": {}, 39 | "json_script": {}, 40 | "floatformat": {}, 41 | "iriencode": {}, 42 | "linenumbers": {}, 43 | "lower": {}, 44 | "make_list": {}, 45 | "slugify": {}, 46 | "stringformat": {}, 47 | "title": {}, 48 | "truncatechars": {}, 49 | "truncatechars_html": {}, 50 | "truncatewords": {}, 51 | "truncatewords_html": {}, 52 | "upper": {}, 53 | "urlencode": {}, 54 | "urlize": {}, 55 | "urlizetrunc": {}, 56 | "wordcount": {}, 57 | "wordwrap": {}, 58 | "ljust": {}, 59 | "rjust": {}, 60 | "center": {}, 61 | "cut": {}, 62 | "escape": {}, 63 | "force_escape": {}, 64 | "linebreaks": {}, 65 | "linebreaksbr": {}, 66 | "safe": {}, 67 | "safeseq": {}, 68 | "striptags": {}, 69 | "dictsort": {}, 70 | "dictsortreversed": {}, 71 | "first": {}, 72 | "join": {}, 73 | "last": {}, 74 | "length": {}, 75 | "length_is": {}, 76 | "random": {}, 77 | "slice": {}, 78 | "unordered_list": {}, 79 | "add": {}, 80 | "get_digit": {}, 81 | "date": {}, 82 | "time": {}, 83 | "timesince": {}, 84 | "timeuntil": {}, 85 | "default": {}, 86 | "default_if_none": {}, 87 | "divisibleby": {}, 88 | "yesno": {}, 89 | "filesizeformat": {}, 90 | "pluralize": {}, 91 | "phone2numeric": {}, 92 | "pprint": {}, 93 | }, 94 | }, 95 | "cache": { 96 | "tags": {"cache": {"inner_tags": [], "closing_tag": "endcache"}}, 97 | "filters": {}, 98 | }, 99 | "i18n": { 100 | "tags": { 101 | "get_available_languages": {}, 102 | "get_language_info": {}, 103 | "get_language_info_list": {}, 104 | "get_current_language": {}, 105 | "get_current_language_bidi": {}, 106 | "trans": {}, 107 | "translate": {}, 108 | "blocktrans": {}, 109 | "blocktranslate": {}, 110 | "language": {"inner_tags": [], "closing_tag": "endlanguage"}, 111 | }, 112 | "filters": { 113 | "language_name": {}, 114 | "language_name_translated": {}, 115 | "language_name_local": {}, 116 | "language_bidi": {}, 117 | }, 118 | }, 119 | "l10n": { 120 | "tags": {"localize": {"inner_tags": [], "closing_tag": "endlocalize"}}, 121 | "filters": {"localize": {}, "unlocalize": {}}, 122 | }, 123 | "static": { 124 | "tags": {"get_static_prefix": {}, "get_media_prefix": {}, "static": {}}, 125 | "filters": {}, 126 | }, 127 | "tz": { 128 | "tags": { 129 | "localtime": {"inner_tags": [], "closing_tag": "endlocaltime"}, 130 | "timezone": {"inner_tags": [], "closing_tag": "endtimezone"}, 131 | "get_current_timezone": {}, 132 | }, 133 | "filters": {"localtime": {}, "utc": {}, "timezone": {}}, 134 | }, 135 | }, 136 | "templates": {}, 137 | "global_template_context": { 138 | "csrf_token": {}, 139 | }, 140 | } 141 | -------------------------------------------------------------------------------- /djlsp/index.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | 3 | 4 | @dataclass 5 | class Variable: 6 | type: str | None = None 7 | docs: str = "" 8 | value: str = "" 9 | 10 | 11 | @dataclass 12 | class Template: 13 | name: str = "" 14 | path: str = "" 15 | extends: str | None = None 16 | blocks: list[str] | None = None 17 | context: dict[str, Variable] = field(default_factory=dict) 18 | 19 | 20 | @dataclass 21 | class Url: 22 | name: str = "" 23 | docs: str = "" 24 | source: str = "" 25 | 26 | 27 | @dataclass 28 | class Tag: 29 | name: str = "" 30 | docs: str = "" 31 | source: str = "" 32 | inner_tags: list[str] = field(default_factory=list) 33 | closing_tag: str = "" 34 | 35 | 36 | @dataclass 37 | class Filter: 38 | name: str = "" 39 | docs: str = "" 40 | source: str = "" 41 | 42 | 43 | @dataclass 44 | class Library: 45 | name: str = "" 46 | tags: dict[str, Tag] = field(default_factory=dict) 47 | filters: dict[str, Filter] = field(default_factory=dict) 48 | 49 | 50 | @dataclass 51 | class WorkspaceIndex: 52 | src_path: str = "" 53 | env_path: str = "" 54 | file_watcher_globs: list[str] = field(default_factory=list) 55 | static_files: list[str] = field(default_factory=list) 56 | urls: dict[str, Url] = field(default_factory=dict) 57 | libraries: dict[str, Library] = field(default_factory=dict) 58 | templates: dict[str, Template] = field(default_factory=dict) 59 | global_template_context: dict[str, Variable] = field(default_factory=dict) 60 | 61 | def update(self, django_data: dict): 62 | self.file_watcher_globs = django_data.get( 63 | "file_watcher_globs", self.file_watcher_globs 64 | ) 65 | self.static_files = django_data.get("static_files", self.static_files) 66 | self.urls = { 67 | name: Url( 68 | name=name, 69 | docs=options.get("docs", ""), 70 | source=options.get("source", ""), 71 | ) 72 | for name, options in django_data.get("urls", {}).items() 73 | } 74 | 75 | self.libraries = { 76 | lib_name: Library( 77 | name=lib_name, 78 | filters={ 79 | name: Filter( 80 | name=name, 81 | docs=filter_options.get("docs", ""), 82 | source=filter_options.get("source", ""), 83 | ) 84 | for name, filter_options in lib_data.get("filters", {}).items() 85 | }, 86 | tags={ 87 | tag: Tag( 88 | name=tag, 89 | docs=tag_options.get("docs"), 90 | source=tag_options.get("source", ""), 91 | inner_tags=tag_options.get("inner_tags", []), 92 | closing_tag=tag_options.get("closing_tag"), 93 | ) 94 | for tag, tag_options in lib_data.get("tags", {}).items() 95 | }, 96 | ) 97 | for lib_name, lib_data in django_data.get("libraries", {}).items() 98 | } 99 | 100 | self.templates = { 101 | name: Template( 102 | name=name, 103 | **{ 104 | **options, 105 | "context": { 106 | var_name: ( 107 | Variable(**type_) 108 | if isinstance(type_, dict) 109 | else Variable(type=type_) 110 | ) 111 | for var_name, type_ in options.get("context", {}).items() 112 | }, 113 | }, 114 | ) 115 | for name, options in django_data.get("templates", {}).items() 116 | } 117 | 118 | self.global_template_context = { 119 | name: ( 120 | Variable(**type_) if isinstance(type_, dict) else Variable(type=type_) 121 | ) 122 | for name, type_ in django_data.get("global_template_context", {}).items() 123 | } 124 | -------------------------------------------------------------------------------- /djlsp/parser.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import logging 3 | import re 4 | import time 5 | from functools import cached_property 6 | from re import Match 7 | from textwrap import dedent 8 | 9 | import jedi 10 | from jedi.api.classes import Completion 11 | from lsprotocol.types import ( 12 | CompletionItem, 13 | CompletionItemKind, 14 | Hover, 15 | Location, 16 | Position, 17 | Range, 18 | ) 19 | from pygls.workspace import TextDocument 20 | 21 | from djlsp.constants import BUILTIN 22 | from djlsp.index import Variable, WorkspaceIndex 23 | 24 | logger = logging.getLogger(__name__) 25 | 26 | RE_TAGS_NO_CONTEXT = re.compile(r"{% ?(end.*|comment|csrf_token|debug|spaceless)") 27 | 28 | _MOST_RECENT_COMPLETIONS: dict[str, Completion] = {} 29 | 30 | 31 | def clear_completions_cache(): 32 | _MOST_RECENT_COMPLETIONS.clear() 33 | 34 | 35 | class TemplateParser: 36 | 37 | def __init__( 38 | self, 39 | workspace_index: WorkspaceIndex, 40 | jedi_project: jedi.Project, 41 | document: TextDocument, 42 | ): 43 | self.workspace_index: WorkspaceIndex = workspace_index 44 | self.jedi_project: jedi.Project = jedi_project 45 | self.document: TextDocument = document 46 | 47 | @cached_property 48 | def loaded_libraries(self): 49 | re_loaded = re.compile(r".*{% ?load ([\w ]*) ?%}$") 50 | loaded = {BUILTIN} 51 | for line in self.document.lines: 52 | if match := re_loaded.match(line): 53 | loaded.update( 54 | [ 55 | lib 56 | for lib in match.group(1).strip().split(" ") 57 | if lib in self.workspace_index.libraries 58 | ] 59 | ) 60 | logger.debug(f"Loaded libraries: {loaded}") 61 | return loaded 62 | 63 | def get_context(self, *, line, character): 64 | # add global template context 65 | context = self.workspace_index.global_template_context.copy() 66 | if "/templates/" in self.document.path: 67 | template_name = self.document.path.split("/templates/", 1)[1] 68 | if template := self.workspace_index.templates.get(template_name): 69 | context.update(template.context) 70 | 71 | # Update type definations based on template type comments 72 | # {# type some_variable: full.python.path.to.class #} 73 | re_type = re.compile(r".*{# type (\w+) ?: ?(.*?) ?#}.*") 74 | for src_line in self.document.lines: 75 | if match := re_type.match(src_line): 76 | variable = match.group(1) 77 | variable_type = match.group(2) 78 | context[variable] = Variable(type=variable_type) 79 | 80 | scoped_tags = [ 81 | ( 82 | "for", 83 | re.compile(r".*{% ?for ([\w ,]*) in ([\w.]+).*$"), 84 | re.compile(r".*{% ?endfor"), 85 | ), 86 | ( 87 | "with", 88 | re.compile(r".*{% ?with (.+) ?%}.*"), 89 | re.compile(r".*{% ?endwith"), 90 | ), 91 | ] 92 | stack = [] 93 | for line_idx, src_line in enumerate(self.document.lines): 94 | # only analyze until the current line 95 | if line and line_idx > line: 96 | break 97 | 98 | for tag_name, re_start, re_end in scoped_tags: 99 | if match := re_start.match(src_line): 100 | stack.append((tag_name, match)) 101 | break 102 | elif match := re_end.match(src_line): 103 | found_tag, _ = stack.pop() 104 | if found_tag != tag_name: 105 | # TODO: show warning to user 106 | logger.debug("Closing tag does not match opening") 107 | break 108 | 109 | if stack: 110 | logger.debug(f"Stack not empty for {line=} {len(stack)=}:") 111 | for tag_name, match in stack: 112 | logger.debug(f" {tag_name} {match!r} {match.groups()!r}") 113 | 114 | if tag_name == "for": 115 | context["forloop"] = Variable(type="_DjangoForLoop") 116 | loop_variables, variable = ( 117 | match.group(1).strip(), 118 | match.group(2).strip(), 119 | ) 120 | variable = self._django_variable_to_python(variable, context) 121 | if "," in loop_variables: 122 | for var_idx, loop_var in enumerate(loop_variables.split(",")): 123 | context[loop_var.strip()] = Variable( 124 | value=f"next(iter({variable}))[{var_idx}]" 125 | ) 126 | else: 127 | context[loop_variables.strip()] = Variable( 128 | value=f"next(iter({variable}))" 129 | ) 130 | 131 | if tag_name == "with": 132 | for assignment in match.group(1).split(" "): 133 | split_assignment = assignment.split("=") 134 | if len(split_assignment) == 2: 135 | context[split_assignment[0].strip()] = Variable( 136 | value=self._django_variable_to_python( 137 | split_assignment[1].strip(), context 138 | ) 139 | ) 140 | 141 | # As tag 142 | # TODO: integrate into scope matcher 143 | re_as = re.compile(r".*{%.*as ([\w ]+) %}.*$") 144 | for src_line in self.document.lines: 145 | if match := re_as.match(src_line): 146 | for variable in match.group(1).split(" "): 147 | if variable_stripped := variable.strip(): 148 | context[variable_stripped] = Variable() 149 | 150 | return context 151 | 152 | def create_jedi_script( 153 | self, 154 | code, 155 | *, 156 | context=None, 157 | line=None, 158 | character=None, 159 | transform_code=True, 160 | execute_last_function=True, 161 | ) -> jedi.Script: 162 | """ 163 | Generate jedi Script based on template context and given code. 164 | """ 165 | if context is None: 166 | context = self.get_context(line=line, character=character) 167 | 168 | script_lines = [] 169 | if re.search(r"{% ?for ", self.document.source): 170 | script_lines.append( 171 | dedent( 172 | ''' 173 | class _DjangoForLoop: 174 | """Django for loop context""" 175 | counter: int 176 | counter0: int 177 | revcounter: int 178 | revcounter0: int 179 | first: bool 180 | last: bool 181 | parentloop: "_DjangoForLoop" 182 | ''' 183 | ) 184 | ) 185 | 186 | for variable_name, variable in context.items(): 187 | if variable.type: 188 | variable_type_aliased = variable.type 189 | # allow to use more complex types by splitting them into segments 190 | # and try to import them separatly 191 | for imp in set(filter(None, re.split(r"\[|\]| |,", variable.type))): 192 | variable_import = ".".join(imp.split(".")[:-1]) 193 | if variable_import == "": 194 | continue 195 | 196 | # create import alias to allow variable to have same name as module 197 | import_alias = ( 198 | "__" + hashlib.md5(variable_import.encode()).hexdigest() 199 | ) 200 | variable_type_aliased = variable_type_aliased.replace( 201 | variable_import, import_alias 202 | ) 203 | script_lines.append(f"import {variable_import} as {import_alias}") 204 | 205 | script_lines.append(f"{variable_name}: {variable_type_aliased}") 206 | else: 207 | script_lines.append(f"{variable_name} = {variable.value or None}") 208 | 209 | # Add user code 210 | if transform_code: 211 | script_lines.append( 212 | self._django_variable_to_python( 213 | code, context, execute_last_function=execute_last_function 214 | ) 215 | ) 216 | logger.debug( 217 | "\n".join(["=== Jedi script ===", *script_lines, "=== End script ==="]) 218 | ) 219 | else: 220 | script_lines.append(code) 221 | 222 | return jedi.Script(code="\n".join(script_lines), project=self.jedi_project) 223 | 224 | def _django_variable_to_python( 225 | self, variable: str, context, *, execute_last_function=True 226 | ): 227 | def join_path(*segments: str): 228 | return ".".join(filter(None, segments)) 229 | 230 | if not variable: 231 | return "" 232 | 233 | start_time = time.time() 234 | res = "" 235 | segments = variable.split(".") 236 | for idx, seg in enumerate(segments): 237 | # django uses abc.0 for list index lookup, replace those with abc[0] 238 | if seg.isdigit() and idx > 0: 239 | res = f"{res}[{seg}]" 240 | continue 241 | 242 | # django does some magic (e.g. call function automaticaly, 243 | # use attribute access for dictionaries, ...) 244 | # try to infer the correct python syntax 245 | infer = self.create_jedi_script( 246 | join_path(res, seg), context=context, transform_code=False 247 | ).infer() 248 | if not infer: 249 | logger.debug( 250 | f"Failed to transform variable '{variable}' (got until {res})" 251 | ) 252 | return variable 253 | 254 | # django calls functions automaticaly 255 | if infer[0].type == "function" and ( 256 | execute_last_function if idx == (len(segments) - 1) else True 257 | ): 258 | res = join_path(res, seg) + "()" 259 | else: 260 | res = join_path(res, seg) 261 | 262 | if variable.endswith("."): 263 | res += "." 264 | 265 | total_time = time.time() - start_time 266 | logger.debug( 267 | f"Variable '{variable}' transformed to '{res}' in {total_time:.4f}s" 268 | ) 269 | 270 | return res 271 | 272 | def _jedi_type_to_completion_kind(self, comp_type: str) -> CompletionItemKind: 273 | """Map Jedi completion types to LSP CompletionItemKind.""" 274 | # https://jedi.readthedocs.io/en/latest/docs/api-classes.html#jedi.api.classes.BaseName.type 275 | kind_mapping = { 276 | "class": CompletionItemKind.Class, 277 | "instance": CompletionItemKind.Variable, 278 | "keyword": CompletionItemKind.Keyword, 279 | "module": CompletionItemKind.Module, 280 | "param": CompletionItemKind.Variable, 281 | "path": CompletionItemKind.File, 282 | "property": CompletionItemKind.Property, 283 | "statement": CompletionItemKind.Variable, 284 | "function": CompletionItemKind.Function, 285 | } 286 | return kind_mapping.get(comp_type, CompletionItemKind.Field) 287 | 288 | ################################################################################### 289 | # Completions 290 | ################################################################################### 291 | def completions(self, line, character): 292 | line_fragment = self.document.lines[line][:character] 293 | matchers = [ 294 | (re.compile(r".*{% ?load ([\w ]*)$"), self.get_load_completions), 295 | (re.compile(r".*{% ?block ([\w]*)$"), self.get_block_completions), 296 | (re.compile(r".*{% ?endblock ([\w]*)$"), self.get_endblock_completions), 297 | (re.compile(r""".*{% ?url ('|")([\w\-:]*)$"""), self.get_url_completions), 298 | ( 299 | re.compile(r".*{% ?static ('|\")([\w\-\.\/]*)$"), 300 | self.get_static_completions, 301 | ), 302 | ( 303 | re.compile(r""".*{% ?(extends|include) ('|")([\w\-:]*)$"""), 304 | self.get_template_completions, 305 | ), 306 | (re.compile(r"^.*{% ?(\w*)$"), self.get_tag_completions), 307 | ( 308 | re.compile(r"^.*({%|{{).*?\|(\w*)$"), 309 | self.get_filter_completions, 310 | ), 311 | ( 312 | re.compile(r"^.*{# type \w+ ?: ?([\w\d_\.]*)$"), 313 | self.get_type_comment_complations, 314 | ), 315 | ( 316 | re.compile(r".*({{|{% \w+ ).*?([\w\d_\.]*)$"), 317 | self.get_context_completions, 318 | ), 319 | ] 320 | 321 | for regex, completion in matchers: 322 | if match := regex.match(line_fragment): 323 | # Sort completions because some editors (Helix) will use order 324 | # as is and wont use sort_text. 325 | return list( 326 | sorted( 327 | completion(match, line=line, character=character), 328 | key=lambda comp: ( 329 | comp.sort_text if comp.sort_text else comp.label 330 | ), 331 | ) 332 | ) 333 | return [] 334 | 335 | def get_load_completions(self, match: Match, **kwargs): 336 | prefix = match.group(1).split(" ")[-1] 337 | logger.debug(f"Find load matches for: {prefix}") 338 | return [ 339 | CompletionItem(label=lib, kind=CompletionItemKind.Module) 340 | for lib in self.workspace_index.libraries.keys() 341 | if lib != BUILTIN and lib.startswith(prefix) 342 | ] 343 | 344 | def get_block_completions(self, match: Match, **kwargs): 345 | prefix = match.group(1).strip() 346 | logger.debug(f"Find block matches for: {prefix}") 347 | block_names = [] 348 | re_extends = re.compile(r""".*{% ?extends ['"](.*)['"] ?%}.*""") 349 | if m := re_extends.search(self.document.source): 350 | logger.debug(f"Finding available block names for {m.group(1)}") 351 | block_names = self._recursive_block_names(m.group(1)) 352 | 353 | used_block_names = [] 354 | re_block = re.compile(r"{% *block ([\w]*) *%}") 355 | for line in self.document.lines: 356 | if matches := re_block.findall(line): 357 | used_block_names.extend(matches) 358 | 359 | return [ 360 | CompletionItem(label=name, kind=CompletionItemKind.Property) 361 | for name in block_names 362 | if name not in used_block_names and name.startswith(prefix) 363 | ] 364 | 365 | def get_endblock_completions(self, match: Match, line, character): 366 | prefix = match.group(1).strip() 367 | logger.debug(f"Find endblock matches for: {prefix}") 368 | items = {} 369 | 370 | re_block = re.compile(r"{% *block ([\w]*) *%}") 371 | for text_line in self.document.lines[:line]: 372 | if matches := re_block.findall(text_line): 373 | for name in reversed(matches): 374 | items.setdefault( 375 | name, 376 | CompletionItem( 377 | label=name, 378 | sort_text=f"{999 - len(items)}: {name}", 379 | kind=CompletionItemKind.Property, 380 | ), 381 | ) 382 | return [item for item in items.values() if item.label.startswith(prefix)] 383 | 384 | def _recursive_block_names(self, template_name, looked_up_templates=None): 385 | looked_up_templates = looked_up_templates if looked_up_templates else [] 386 | looked_up_templates.append(template_name) 387 | 388 | block_names = [] 389 | if template := self.workspace_index.templates.get(template_name): 390 | block_names.extend(template.blocks) 391 | if template.extends and template.extends not in looked_up_templates: 392 | block_names.extend( 393 | self._recursive_block_names(template.extends, looked_up_templates) 394 | ) 395 | return list(set(block_names)) 396 | 397 | def get_static_completions(self, match: Match, **kwargs): 398 | prefix = match.group(2) 399 | logger.debug(f"Find static matches for: {prefix}") 400 | return [ 401 | CompletionItem(label=static_file, kind=CompletionItemKind.File) 402 | for static_file in self.workspace_index.static_files 403 | if static_file.startswith(prefix) 404 | ] 405 | 406 | def get_url_completions(self, match: Match, **kwargs): 407 | prefix = match.group(2) 408 | logger.debug(f"Find url matches for: {prefix}") 409 | return [ 410 | CompletionItem( 411 | label=url.name, 412 | documentation=url.docs, 413 | kind=CompletionItemKind.Reference, 414 | ) 415 | for url in self.workspace_index.urls.values() 416 | if url.name.startswith(prefix) 417 | ] 418 | 419 | def get_template_completions(self, match: Match, **kwargs): 420 | prefix = match.group(3) 421 | logger.debug(f"Find {match.group(1)} matches for: {prefix}") 422 | return [ 423 | CompletionItem(label=template, kind=CompletionItemKind.File) 424 | for template in self.workspace_index.templates 425 | if template.startswith(prefix) 426 | ] 427 | 428 | def get_tag_completions(self, match: Match, line, character): 429 | prefix = match.group(1) 430 | logger.debug(f"Find tag matches for: {prefix}") 431 | 432 | # Get all avaible tags in template 433 | available_tags = { 434 | tag.name: tag 435 | for lib_name in self.loaded_libraries 436 | for tag in self.workspace_index.libraries.get(lib_name).tags.values() 437 | } 438 | 439 | # Collect all tags above the current cursor position 440 | collected_tags = [] 441 | tag_re = re.compile(r"{% ?(\w+).*?%}") 442 | for text_line in self.document.lines[:line]: 443 | for tag_name in tag_re.findall(text_line): 444 | if tag := available_tags.get(tag_name): 445 | collected_tags.append(tag) 446 | 447 | # Add all tag completions 448 | tags = {} 449 | for tag in available_tags.values(): 450 | tags[tag.name] = CompletionItem( 451 | label=tag.name, 452 | documentation=tag.docs, 453 | sort_text=f"999: {tag.name}", 454 | kind=CompletionItemKind.Keyword, 455 | ) 456 | 457 | # Add all inner/closing tags 458 | for index, tag in enumerate(reversed(collected_tags)): 459 | for tag_name in filter(None, [*tag.inner_tags, tag.closing_tag]): 460 | tags.setdefault( 461 | tag_name, 462 | CompletionItem( 463 | label=tag_name, 464 | sort_text=f"{index}: {tag_name}", 465 | kind=CompletionItemKind.Keyword, 466 | ), 467 | ) 468 | 469 | return [tag for tag in tags.values() if tag.label.startswith(prefix)] 470 | 471 | def get_filter_completions(self, match: Match, **kwargs): 472 | prefix = match.group(2) 473 | logger.debug(f"Find filter matches for: {prefix}") 474 | filters = [] 475 | for lib_name in self.loaded_libraries: 476 | if lib := self.workspace_index.libraries.get(lib_name): 477 | filters.extend( 478 | [ 479 | CompletionItem( 480 | label=filt.name, 481 | documentation=filt.docs, 482 | kind=CompletionItemKind.Function, 483 | ) 484 | for filt in lib.filters.values() 485 | ] 486 | ) 487 | return [ 488 | filter_name 489 | for filter_name in filters 490 | if filter_name.label.startswith(prefix) 491 | ] 492 | 493 | def get_type_comment_complations(self, match: Match, **kwargs): 494 | prefix = match.group(1) 495 | logger.debug(f"Find type comment matches for: {prefix}") 496 | 497 | if "." in prefix: 498 | from_part = ".".join(prefix.split(".")[:-1]) 499 | import_part = prefix.split(".")[-1] 500 | code = f"from {from_part} import {import_part}" 501 | else: 502 | code = f"import {prefix}" 503 | 504 | return [ 505 | CompletionItem( 506 | label=comp.name, kind=self._jedi_type_to_completion_kind(comp.type) 507 | ) 508 | for comp in self.create_jedi_script(code, **kwargs).complete() 509 | ] 510 | 511 | def get_context_completions(self, match: Match, **kwargs): 512 | prefix = match.group(2) 513 | logger.debug(f"Find context matches for: {prefix}") 514 | 515 | if RE_TAGS_NO_CONTEXT.match(match.group(1)): 516 | return [] 517 | 518 | def get_sort_text(comp): 519 | type_sort = {"statement": "1", "property": "2"}.get(comp.type, "9") 520 | return f"{type_sort}-{comp.name}".lower() 521 | 522 | if "." in prefix: 523 | # Find . completions with Jedi 524 | completions = [] 525 | for comp in self.create_jedi_script(prefix, **kwargs).complete(): 526 | if comp.name.startswith("_"): 527 | continue 528 | 529 | _MOST_RECENT_COMPLETIONS[comp.name] = comp 530 | completions.append( 531 | CompletionItem( 532 | label=comp.name, 533 | sort_text=get_sort_text(comp), 534 | kind=self._jedi_type_to_completion_kind(comp.type), 535 | ) 536 | ) 537 | return completions 538 | else: 539 | # Only context completions 540 | return [ 541 | CompletionItem( 542 | label=var_name, 543 | sort_text=var_name.lower(), 544 | kind=CompletionItemKind.Variable, 545 | detail=f"{var_name}: {var.type}", 546 | documentation=var.docs, 547 | ) 548 | for var_name, var in self.get_context(**kwargs).items() 549 | if var_name.startswith(prefix) 550 | ] 551 | 552 | @staticmethod 553 | def resolve_completion(item: CompletionItem): 554 | if not item.documentation and item.label in _MOST_RECENT_COMPLETIONS: 555 | completion = _MOST_RECENT_COMPLETIONS[item.label] 556 | item.detail = f"({completion.type}) {completion.name}" 557 | item.documentation = completion.docstring() 558 | 559 | return item 560 | 561 | ################################################################################### 562 | # Hover 563 | ################################################################################### 564 | def hover(self, line, character): 565 | line_fragment = self.document.lines[line][:character] 566 | matchers = [ 567 | (re.compile(r""".*{% ?url ('|")([\w\-:]*)$"""), self.get_url_hover), 568 | (re.compile(r"^.*({%|{{) ?[\w \.\|]*\|(\w*)$"), self.get_filter_hover), 569 | (re.compile(r"^.*{% ?(\w*)$"), self.get_tag_hover), 570 | ( 571 | re.compile(r".*({{|{% \w+ ).*?([\w\d_\.]*)$"), 572 | self.get_context_hover, 573 | ), 574 | ] 575 | for regex, hover in matchers: 576 | if match := regex.match(line_fragment): 577 | return hover(line, character, match) 578 | return None 579 | 580 | def get_url_hover(self, line, character, match: Match): 581 | full_match = self._get_full_hover_name( 582 | line, character, match.group(2), regex=r"^([\w\d:\-]+).*" 583 | ) 584 | logger.debug(f"Find url hover for: {full_match}") 585 | if url := self.workspace_index.urls.get(full_match): 586 | return Hover( 587 | contents=url.docs, 588 | ) 589 | 590 | def get_filter_hover(self, line, character, match: Match): 591 | filter_name = self._get_full_hover_name(line, character, match.group(2)) 592 | logger.debug(f"Find filter hover for: {filter_name}") 593 | for lib in self.workspace_index.libraries.values(): 594 | if lib.name in self.loaded_libraries and filter_name in lib.filters: 595 | return Hover( 596 | contents=lib.filters[filter_name].docs, 597 | ) 598 | return None 599 | 600 | def get_tag_hover(self, line, character, match: Match): 601 | tag_name = self._get_full_hover_name(line, character, match.group(1)) 602 | logger.debug(f"Find tag hover for: {tag_name}") 603 | for lib in self.workspace_index.libraries.values(): 604 | if lib.name in self.loaded_libraries and tag_name in lib.tags: 605 | return Hover( 606 | contents=lib.tags[tag_name].docs, 607 | ) 608 | return None 609 | 610 | def get_context_hover(self, line, character, match: Match): 611 | context_name = self._get_full_hover_name(line, character, match.group(2)) 612 | logger.debug(f"Find context hover for: {context_name}") 613 | 614 | # first try to resolve variable type locally 615 | context = self.get_context(line=line, character=character) 616 | if context_name in context and context[context_name].type: 617 | return Hover( 618 | contents=( 619 | f"(variable) {context_name}: {context[context_name].type}" 620 | f"\n\n{context[context_name].docs}" 621 | ).strip(), 622 | ) 623 | 624 | # but if not possible, use jedi 625 | if hlp := self.create_jedi_script( 626 | context_name, line=line, character=character, execute_last_function=False 627 | ).help(): 628 | return Hover( 629 | contents=( 630 | f"({hlp[0].type}) {hlp[0].name}: {hlp[0].get_type_hint()}" 631 | f"\n\n{hlp[0].docstring()}" 632 | ).strip(), 633 | ) 634 | 635 | return None 636 | 637 | def _get_full_hover_name(self, line, character, first_part, regex=r"^([\w\d]+).*"): 638 | if match_after := re.match(regex, self.document.lines[line][character:]): 639 | return first_part + match_after.group(1) 640 | return first_part 641 | 642 | ################################################################################### 643 | # Goto definition 644 | ################################################################################### 645 | def goto_definition(self, line, character): 646 | line_fragment = self.document.lines[line][:character] 647 | matchers = [ 648 | ( 649 | re.compile(r""".*{% ?(extends|include) ('|")([\w\-\./]*)$"""), 650 | self.get_template_definition, 651 | ), 652 | (re.compile(r""".*{% ?url ('|")([\w\-:]*)$"""), self.get_url_definition), 653 | (re.compile(r"^.*{% ?(\w*)$"), self.get_tag_definition), 654 | (re.compile(r"^.*({%|{{).*?\|(\w*)$"), self.get_filter_definition), 655 | ( 656 | re.compile(r".*({{|{% \w+ ).*?([\w\d_\.]*)$"), 657 | self.get_context_definition, 658 | ), 659 | ] 660 | for regex, definition in matchers: 661 | if match := regex.match(line_fragment): 662 | return definition(line, character, match) 663 | return None 664 | 665 | def create_location(self, location, path, line): 666 | root_path = ( 667 | self.workspace_index.src_path 668 | if location == "src" 669 | else self.workspace_index.env_path 670 | ) 671 | return Location( 672 | uri=f"file://{root_path}/{path}", 673 | range=Range( 674 | start=Position(line=int(line), character=0), 675 | end=Position(line=int(line), character=0), 676 | ), 677 | ) 678 | 679 | def get_template_definition(self, line, character, match: Match): 680 | if match_after := re.match( 681 | r"""^(.*)('|").*""", self.document.lines[line][character:] 682 | ): 683 | template_name = match.group(3) + match_after.group(1) 684 | logger.debug(f"Find template goto definition for: {template_name}") 685 | if template := self.workspace_index.templates.get(template_name): 686 | location, path = template.path.split(":") 687 | return self.create_location(location, path, 0) 688 | 689 | def get_url_definition(self, line, character, match: Match): 690 | full_match = self._get_full_definition_name( 691 | line, character, match.group(2), regex=r"^([\w\d:\-]+).*" 692 | ) 693 | logger.debug(f"Find url goto definition for: {full_match}") 694 | if url := self.workspace_index.urls.get(full_match): 695 | if url.source: 696 | return self.create_location(*url.source.split(":")) 697 | 698 | def get_tag_definition(self, line, character, match: Match): 699 | full_match = self._get_full_definition_name(line, character, match.group(1)) 700 | logger.debug(f"Find tag goto definition for: {full_match}") 701 | for lib in self.loaded_libraries: 702 | if tag := self.workspace_index.libraries[lib].tags.get(full_match): 703 | if tag.source: 704 | return self.create_location(*tag.source.split(":")) 705 | 706 | def get_filter_definition(self, line, character, match: Match): 707 | full_match = self._get_full_definition_name(line, character, match.group(2)) 708 | logger.debug(f"Find filter goto definition for: {full_match}") 709 | for lib in self.loaded_libraries: 710 | if filter_ := self.workspace_index.libraries[lib].filters.get(full_match): 711 | if filter_.source: 712 | return self.create_location(*filter_.source.split(":")) 713 | 714 | def get_context_definition(self, line, character, match: Match): 715 | first_match = match.group(2) 716 | full_match = self._get_full_definition_name(line, character, first_match) 717 | logger.debug(f"Find context goto definition for: {full_match}") 718 | if gotos := self.create_jedi_script( 719 | full_match, line=line, character=character 720 | ).goto(column=len(first_match)): 721 | goto = gotos[0] 722 | if goto.module_name == "__main__": 723 | # Location is in fake script get type location 724 | if infers := goto.infer(): 725 | goto = infers[0] 726 | else: 727 | return None 728 | return Location( 729 | uri=f"file://{goto.module_path}", 730 | range=Range( 731 | start=Position(line=goto.line, character=goto.column), 732 | end=Position(line=goto.line, character=goto.column), 733 | ), 734 | ) 735 | 736 | def _get_full_definition_name( 737 | self, line, character, first_part, regex=r"^([\w\d]+).*" 738 | ): 739 | if match_after := re.match(regex, self.document.lines[line][character:]): 740 | return first_part + match_after.group(1) 741 | return first_part 742 | -------------------------------------------------------------------------------- /djlsp/scripts/django-collector.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import importlib 3 | import inspect 4 | import json 5 | import logging 6 | import os 7 | import re 8 | import sys 9 | from dataclasses import dataclass 10 | from unittest.mock import MagicMock, patch 11 | 12 | import django 13 | from django.apps import apps 14 | from django.conf import settings 15 | from django.contrib.auth import get_user_model 16 | from django.contrib.staticfiles.finders import get_finders 17 | from django.template.backends.django import get_installed_libraries 18 | from django.template.engine import Engine 19 | from django.template.library import InvalidTemplateLibrary 20 | from django.template.utils import get_app_template_dirs 21 | from django.urls import URLPattern, URLResolver 22 | from django.views.generic import View 23 | from django.views.generic.detail import SingleObjectMixin 24 | from django.views.generic.edit import FormMixin 25 | from django.views.generic.list import MultipleObjectMixin 26 | 27 | logger = logging.getLogger(__name__) 28 | 29 | # Some tags are added with a Node, like end*, elif else. 30 | # TODO: Find a way of collecting these, for now hardcoded list 31 | LIBRARIES_NODE_TAGS = { 32 | "__builtins__": { 33 | "autoescape": { 34 | "closing_tag": "endautoescape", 35 | }, 36 | "filter": { 37 | "closing_tag": "endfilter", 38 | }, 39 | "for": { 40 | "inner_tags": [ 41 | "empty", 42 | ], 43 | "closing_tag": "endfor", 44 | }, 45 | "if": { 46 | "inner_tags": [ 47 | "else", 48 | "elif", 49 | ], 50 | "closing_tag": "endif", 51 | }, 52 | "ifchanged": { 53 | "closing_tag": "endifchanged", 54 | }, 55 | "spaceless": { 56 | "closing_tag": "endspaceless", 57 | }, 58 | "verbatim": { 59 | "closing_tag": "endverbatim", 60 | }, 61 | "with": { 62 | "closing_tag": "endwith", 63 | }, 64 | "block": { 65 | "closing_tag": "endblock", 66 | }, 67 | "comment": { 68 | "closing_tag": "endcomment", 69 | }, 70 | }, 71 | "cache": { 72 | "cache": { 73 | "closing_tag": "endcache", 74 | } 75 | }, 76 | "i18n": { 77 | "language": { 78 | "closing_tag": "endlanguage", 79 | }, 80 | "blocktrans": { 81 | "inner_tags": ["plural"], 82 | "closing_tag": "endblocktrans", 83 | }, 84 | "blocktranslate": { 85 | "inner_tags": ["plural"], 86 | "closing_tag": "endblocktranslate", 87 | }, 88 | }, 89 | "l10n": { 90 | "localize": { 91 | "closing_tag": "endlocalize", 92 | } 93 | }, 94 | "tz": { 95 | "localtime": { 96 | "closing_tag": "endlocaltime", 97 | }, 98 | "timezone": { 99 | "closing_tag": "endtimezone", 100 | }, 101 | }, 102 | } 103 | 104 | # Context processors are functions and therefore hard to parse 105 | # Use hardcoded mapping for know context processors. 106 | TEMPLATE_CONTEXT_PROCESSORS = { 107 | # Django 108 | "django.template.context_processors.csrf": { 109 | "csrf_token": None, 110 | }, 111 | "django.template.context_processors.debug": { 112 | "debug": None, 113 | "sql_queries": None, 114 | }, 115 | "django.template.context_processors.i18n": { 116 | "LANGUAGES": None, 117 | "LANGUAGE_CODE": None, 118 | "LANGUAGE_BIDI": None, 119 | }, 120 | "django.template.context_processors.tz": { 121 | "TIME_ZONE": None, 122 | }, 123 | "django.template.context_processors.static": { 124 | "STATIC_URL": None, 125 | }, 126 | "django.template.context_processors.media": { 127 | "MEDIA_URL": None, 128 | }, 129 | "django.template.context_processors.request": { 130 | "request": "django.http.request.HttpRequest", 131 | }, 132 | # Django: auth 133 | "django.contrib.auth.context_processors.auth": { 134 | "user": None, 135 | "perms": None, 136 | }, 137 | # Django: messages 138 | "django.contrib.messages.context_processors.messages": { 139 | "messages": None, 140 | "DEFAULT_MESSAGE_LEVELS": None, 141 | }, 142 | # Wagtail: settings 143 | "wagtail.contrib.settings.context_processors.settings": { 144 | # TODO: add fake settings object type with reference to models 145 | "settings": None, 146 | }, 147 | # Oscar 148 | "oscar.core.context_processors.metadata": { 149 | "shop_name": None, 150 | "shop_tagline": None, 151 | "homepage_url": None, 152 | "language_neutral_url_path": None, 153 | }, 154 | "oscar.apps.search.context_processors.search_form": { 155 | "search_form": None, 156 | }, 157 | "oscar.apps.checkout.context_processors.checkout": { 158 | "anon_checkout_allowed": None, 159 | }, 160 | "oscar.apps.communication.notifications.context_processors.notifications": { 161 | "num_unread_notifications": None, 162 | }, 163 | # Django CMS 164 | "cms.context_processors.cms_settings": { 165 | "cms_menu_renderer": None, 166 | "CMS_MEDIA_URL": None, 167 | "CMS_TEMPLATE": None, 168 | }, 169 | } 170 | 171 | 172 | ####################################################################################### 173 | # Index Types 174 | ####################################################################################### 175 | @dataclass 176 | class Template: 177 | path: str = "" 178 | name: str = "" 179 | content: str = "" 180 | 181 | 182 | ####################################################################################### 183 | # Index collector 184 | ####################################################################################### 185 | class DjangoIndexCollector: 186 | re_extends = re.compile(r""".*{% ?extends ['"](.*)['"] ?%}.*""") 187 | re_block = re.compile(r".*{% ?block (\w*) ?%}.*") 188 | 189 | def __init__(self, project_src_path): 190 | self.project_src_path = project_src_path 191 | 192 | # Index data 193 | self.file_watcher_globs = [] 194 | self.static_files = [] 195 | self.urls = {} 196 | self.libraries = {} 197 | self.templates: dict[str, Template] = {} 198 | self.global_template_context = {} 199 | 200 | def collect(self): 201 | self.file_watcher_globs = self.get_file_watcher_globs() 202 | self.static_files = self.get_static_files() 203 | self.templates = self.get_templates() 204 | self.urls = self.get_urls() 205 | self.libraries = self.get_libraries() 206 | self.global_template_context = self.get_global_template_context() 207 | 208 | # Third party collectors 209 | self.collect_for_wagtail() 210 | 211 | def to_json(self): 212 | return json.dumps( 213 | { 214 | "file_watcher_globs": self.file_watcher_globs, 215 | "static_files": self.static_files, 216 | "urls": self.urls, 217 | "libraries": self.libraries, 218 | "templates": self.templates, 219 | "global_template_context": self.global_template_context, 220 | }, 221 | indent=4, 222 | ) 223 | 224 | def get_source_from_type(self, type_): 225 | def unwrap(func): 226 | while hasattr(func, "__wrapped__"): 227 | func = func.__wrapped__ 228 | return func 229 | 230 | type_ = unwrap(type_) 231 | 232 | try: 233 | source_file = inspect.getsourcefile(type_) 234 | line = inspect.getsourcelines(type_)[1] 235 | except Exception as e: 236 | logger.error(e) 237 | return "" 238 | 239 | if source_file.startswith(self.project_src_path): 240 | path = source_file.removeprefix(self.project_src_path).lstrip("/") 241 | return f"src:{path}:{line}" 242 | elif source_file.startswith(sys.prefix): 243 | path = source_file.removeprefix(sys.prefix).lstrip("/") 244 | return f"env:{path}:{line}" 245 | return "" 246 | 247 | def get_type_full_name(self, type_): 248 | return f"{type_.__module__}.{type_.__name__}" 249 | 250 | # File watcher globs 251 | # --------------------------------------------------------------------------------- 252 | def get_file_watcher_globs(self): 253 | """ 254 | File watcher glob patterns used to trigger this collector script 255 | 256 | https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern 257 | """ 258 | patterns = [ 259 | "**/templates/**", 260 | "**/templatetags/**", 261 | "**/static/**", 262 | ] 263 | 264 | for static_path in settings.STATICFILES_DIRS: 265 | static_folder = os.path.basename(static_path) 266 | if static_folder != "static": 267 | patterns.append(f"**/{static_folder}/**") 268 | 269 | for template_path in [ 270 | *Engine.get_default().dirs, 271 | *get_app_template_dirs("templates"), 272 | ]: 273 | template_folder = os.path.basename(template_path) 274 | if template_folder != "templates": 275 | patterns.append(f"**/{template_folder}/**") 276 | 277 | return patterns 278 | 279 | # Static files 280 | # --------------------------------------------------------------------------------- 281 | def get_static_files(self): 282 | # TODO: Add option to ignore some static folders 283 | # (like static that is generated with a JS bundler) 284 | static_paths = [] 285 | for finder in get_finders(): 286 | for path, _ in finder.list(None): 287 | static_paths.append(path) 288 | return static_paths 289 | 290 | # Urls 291 | # --------------------------------------------------------------------------------- 292 | def get_urls(self): 293 | try: 294 | urlpatterns = __import__(settings.ROOT_URLCONF, {}, {}, [""]).urlpatterns 295 | except Exception: 296 | return {} 297 | 298 | def recursive_get_views(urlpatterns, namespace=None, pattern=""): 299 | views = {} 300 | for p in urlpatterns: 301 | if isinstance(p, URLPattern): 302 | # TODO: Get view path/line and template context 303 | if not p.name: 304 | name = p.name 305 | elif namespace: 306 | name = "{0}:{1}".format(namespace, p.name) 307 | else: 308 | name = p.name 309 | 310 | if name: 311 | callback = getattr(p.callback, "view_class", p.callback) 312 | try: 313 | self.add_template_context_for_view(callback) 314 | except Exception: 315 | pass 316 | views[name] = { 317 | "docs": f"{pattern}{p.pattern}", 318 | "source": self.get_source_from_type(callback), 319 | } 320 | elif isinstance(p, URLResolver): 321 | try: 322 | patterns = p.url_patterns 323 | except ImportError: 324 | continue 325 | if namespace and p.namespace: 326 | _namespace = "{0}:{1}".format(namespace, p.namespace) 327 | else: 328 | _namespace = p.namespace or namespace 329 | views.update( 330 | recursive_get_views( 331 | patterns, 332 | namespace=_namespace, 333 | pattern=f"{pattern}{p.pattern}", 334 | ) 335 | ) 336 | return views 337 | 338 | return recursive_get_views(urlpatterns) 339 | 340 | # Libaries 341 | # --------------------------------------------------------------------------------- 342 | def get_libraries(self): 343 | libraries = { 344 | "__builtins__": { 345 | "tags": {}, 346 | "filters": {}, 347 | } 348 | } 349 | 350 | # Collect builtins 351 | for lib_mod_path in Engine.get_default().builtins: 352 | lib = importlib.import_module(lib_mod_path).register 353 | parsed_lib = self._parse_library(lib) 354 | libraries["__builtins__"]["tags"].update(parsed_lib["tags"]) 355 | libraries["__builtins__"]["filters"].update(parsed_lib["filters"]) 356 | 357 | # Get Django templatetags 358 | django_path = inspect.getabsfile(django.templatetags) 359 | django_mod_files = os.listdir(os.path.dirname(django_path)) 360 | for django_lib in [ 361 | i[:-3] for i in django_mod_files if i.endswith(".py") and i[0] != "_" 362 | ]: 363 | try: 364 | lib = get_installed_libraries()[django_lib] 365 | lib = importlib.import_module(lib).register 366 | libraries[django_lib] = self._parse_library(lib) 367 | except (InvalidTemplateLibrary, KeyError) as e: 368 | logger.error(f"Failed to parse django templatetag {django_lib}: {e}") 369 | continue 370 | 371 | for app_config in apps.get_app_configs(): 372 | app = app_config.name 373 | try: 374 | templatetag_mod = __import__(app + ".templatetags", {}, {}, [""]) 375 | except ImportError: 376 | continue 377 | 378 | try: 379 | mod_path = inspect.getabsfile(templatetag_mod) 380 | except TypeError as e: 381 | logger.error(f"Failed getting path for ({app}) templatetags: {e}") 382 | continue 383 | mod_files = os.listdir(os.path.dirname(mod_path)) 384 | tag_files = [i[:-3] for i in mod_files if i.endswith(".py") and i[0] != "_"] 385 | 386 | for taglib in tag_files: 387 | try: 388 | lib = get_installed_libraries()[taglib] 389 | lib = importlib.import_module(lib).register 390 | except (InvalidTemplateLibrary, KeyError) as e: 391 | logger.error(f"Failed to parse library ({taglib}): {e}") 392 | continue 393 | 394 | libraries[taglib] = self._parse_library(lib) 395 | 396 | # Add node tags 397 | for lib_name, tags in LIBRARIES_NODE_TAGS.items(): 398 | if lib_name in libraries: 399 | for tag, options in tags.items(): 400 | if tag in libraries[lib_name]["tags"]: 401 | libraries[lib_name]["tags"][tag]["inner_tags"] = options.get( 402 | "inner_tags", [] 403 | ) 404 | libraries[lib_name]["tags"][tag]["closing_tag"] = options.get( 405 | "closing_tag" 406 | ) 407 | 408 | return libraries 409 | 410 | def _parse_library(self, lib) -> dict: 411 | return { 412 | "tags": { 413 | name: { 414 | "docs": func.__doc__.strip() if func.__doc__ else "", 415 | "source": self.get_source_from_type(func), 416 | } 417 | for name, func in lib.tags.items() 418 | }, 419 | "filters": { 420 | name: { 421 | "docs": func.__doc__.strip() if func.__doc__ else "", 422 | "source": self.get_source_from_type(func), 423 | } 424 | for name, func in lib.filters.items() 425 | }, 426 | } 427 | 428 | # Templates 429 | # --------------------------------------------------------------------------------- 430 | def get_templates(self): 431 | template_files = {} 432 | default_engine = Engine.get_default() 433 | for templates_dir in [ 434 | *default_engine.dirs, 435 | *get_app_template_dirs("templates"), 436 | ]: 437 | for root, dirs, files in os.walk(templates_dir): 438 | for file in files: 439 | template_name = os.path.relpath( 440 | os.path.join(root, file), templates_dir 441 | ) 442 | 443 | if template_name in template_files: 444 | # Skip already procecesed template 445 | # (template have duplicates because other apps can override) 446 | continue 447 | 448 | # Get used template (other apps can override templates) 449 | template_files[template_name] = self._parse_template( 450 | self._get_template(default_engine, template_name), 451 | ) 452 | return template_files 453 | 454 | def add_template_context_for_view(self, view): 455 | if not issubclass(view, View): 456 | # Ensure only class-based views (CBVs) are allowed; function-based 457 | # views (FBVs) are not supported 458 | return 459 | 460 | view_obj = view(request=MagicMock()) 461 | 462 | try: 463 | template_name = view_obj.get_template_names()[0] 464 | except Exception: 465 | template_name = getattr(view, "template_name", None) 466 | 467 | if template_name in self.templates: 468 | if issubclass(view, SingleObjectMixin) and hasattr(view, "model"): 469 | context = {"object": self.get_type_full_name(view.model)} 470 | try: 471 | context_name = view_obj.get_context_object_name(view.model) 472 | if context_name: 473 | context[context_name] = context["object"] 474 | except Exception: 475 | pass 476 | self.templates[template_name]["context"].update(context) 477 | if issubclass(view, MultipleObjectMixin): 478 | try: 479 | paginator = self.get_type_full_name(view.paginator_class) 480 | except Exception: 481 | paginator = "django.core.paginator.Paginator" 482 | 483 | self.templates[template_name]["context"].update( 484 | { 485 | "paginator": paginator, 486 | "page_obj": "django.core.paginator.Page", 487 | "is_paginated": "bool", 488 | "object_list": "django.db.models.QuerySet", 489 | } 490 | ) 491 | if issubclass(view, FormMixin) and hasattr(view, "form_class"): 492 | self.templates[template_name]["context"].update( 493 | {"form": self.get_type_full_name(view.form_class)} 494 | ) 495 | 496 | def _parse_template(self, template: Template) -> dict: 497 | extends = None 498 | blocks = set() 499 | for line in template.content.splitlines(): 500 | if match := self.re_extends.match(line): 501 | extends = match.group(1) 502 | if match := self.re_block.match(line): 503 | blocks.add(match.group(1)) 504 | 505 | path = "" 506 | if template.path.startswith(self.project_src_path): 507 | path = ( 508 | f"src:{template.path.removeprefix(self.project_src_path).lstrip('/')}" 509 | ) 510 | elif template.path.startswith(sys.prefix): 511 | path = f"env:{template.path.removeprefix(sys.prefix).lstrip('/')}" 512 | 513 | return { 514 | "path": path, 515 | "extends": extends, 516 | "blocks": list(blocks), 517 | "context": {}, 518 | } 519 | 520 | def _get_template(self, engine: Engine, template_name: str) -> Template: 521 | for loader in engine.template_loaders: 522 | for origin in loader.get_template_sources(template_name): 523 | try: 524 | return Template( 525 | path=str(origin), 526 | name=template_name, 527 | content=loader.get_contents(origin), 528 | ) 529 | except Exception: 530 | pass 531 | return Template(name=template_name) 532 | 533 | # Global context 534 | # --------------------------------------------------------------------------------- 535 | def get_global_template_context(self): 536 | global_context = { 537 | # builtins 538 | "True": None, 539 | "False": None, 540 | "None": None, 541 | } 542 | 543 | # Update object types 544 | TEMPLATE_CONTEXT_PROCESSORS["django.contrib.auth.context_processors.auth"][ 545 | "user" 546 | ] = f"{get_user_model().__module__}.{get_user_model().__name__}" 547 | 548 | for context_processor in Engine.get_default().template_context_processors: 549 | module_path = ".".join( 550 | [context_processor.__module__, context_processor.__name__] 551 | ) 552 | if context := TEMPLATE_CONTEXT_PROCESSORS.get(module_path): 553 | global_context.update(context) 554 | return global_context 555 | 556 | # Third party: Wagtail 557 | # --------------------------------------------------------------------------------- 558 | def collect_for_wagtail(self): 559 | try: 560 | from wagtail.models import Page 561 | except ImportError: 562 | return 563 | for model in apps.get_models(): 564 | if issubclass(model, Page) and model.template in self.templates: 565 | self.templates[model.template]["context"].update( 566 | { 567 | "page": model.__module__ + "." + model.__name__, 568 | "self": model.__module__ + "." + model.__name__, 569 | } 570 | ) 571 | if model.context_object_name: 572 | self.templates[model.template]["context"][ 573 | model.context_object_name 574 | ] = (model.__module__ + "." + model.__name__) 575 | 576 | 577 | ####################################################################################### 578 | # CLI 579 | ####################################################################################### 580 | def get_default_django_settings_module(): 581 | try: 582 | # Patch django execute to prevent it from running when calling main 583 | with patch( 584 | "django.core.management.execute_from_command_line", return_value=None 585 | ): 586 | from manage import main 587 | 588 | # Need to run main becuase default env is set in main function 589 | main() 590 | 591 | return os.getenv("DJANGO_SETTINGS_MODULE") 592 | except ImportError: 593 | return "" 594 | 595 | 596 | if __name__ == "__main__": 597 | parser = argparse.ArgumentParser( 598 | description=""" 599 | Collect django project information for LSP. 600 | pure python script that is runned in project environment for using django. 601 | """ 602 | ) 603 | parser.add_argument("--django-settings-module", action="store", type=str) 604 | parser.add_argument("--project-src", action="store", type=str) 605 | args = parser.parse_args() 606 | 607 | project_src_path = args.project_src if args.project_src else os.getcwd() 608 | sys.path.insert(0, project_src_path) 609 | 610 | django_settings_module = ( 611 | args.django_settings_module 612 | if args.django_settings_module 613 | else get_default_django_settings_module() 614 | ) 615 | if args.django_settings_module: 616 | os.environ.setdefault( 617 | "DJANGO_SETTINGS_MODULE", 618 | django_settings_module, 619 | ) 620 | 621 | # Enable error logging to stderr 622 | logging.basicConfig( 623 | level=logging.ERROR, 624 | format="%(message)s", 625 | handlers=[logging.StreamHandler(sys.stderr)], 626 | ) 627 | 628 | # redirect stdout to stderr when loading the django application, 629 | # so that only the collected json gets printed to stdout 630 | stdout = sys.stdout 631 | sys.stdout = sys.stderr 632 | 633 | django.setup() 634 | 635 | collector = DjangoIndexCollector(project_src_path) 636 | collector.collect() 637 | 638 | print(collector.to_json(), file=stdout) 639 | -------------------------------------------------------------------------------- /djlsp/server.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import hashlib 3 | import http.client 4 | import json 5 | import logging 6 | import os 7 | import shutil 8 | import subprocess 9 | import tempfile 10 | import time 11 | import uuid 12 | from functools import cached_property 13 | 14 | import jedi 15 | from lsprotocol.types import ( 16 | COMPLETION_ITEM_RESOLVE, 17 | INITIALIZE, 18 | TEXT_DOCUMENT_COMPLETION, 19 | TEXT_DOCUMENT_DEFINITION, 20 | TEXT_DOCUMENT_HOVER, 21 | WORKSPACE_DID_CHANGE_WATCHED_FILES, 22 | CompletionItem, 23 | CompletionList, 24 | CompletionOptions, 25 | CompletionParams, 26 | DefinitionParams, 27 | DidChangeWatchedFilesParams, 28 | DidChangeWatchedFilesRegistrationOptions, 29 | FileSystemWatcher, 30 | HoverParams, 31 | InitializeParams, 32 | Registration, 33 | RegistrationParams, 34 | ) 35 | from pygls.server import LanguageServer 36 | 37 | from djlsp import __version__ 38 | from djlsp.constants import FALLBACK_DJANGO_DATA 39 | from djlsp.index import WorkspaceIndex 40 | from djlsp.parser import TemplateParser, clear_completions_cache 41 | 42 | logger = logging.getLogger(__name__) 43 | 44 | 45 | DJANGO_COLLECTOR_SCRIPT_PATH = os.path.join( 46 | os.path.dirname(os.path.realpath(__file__)), 47 | "scripts", 48 | "django-collector.py", 49 | ) 50 | 51 | DEFAULT_ENV_DIRECTORIES = [ 52 | "env", 53 | ".env", 54 | "venv", 55 | ".venv", 56 | ] 57 | 58 | 59 | class DjangoTemplateLanguageServer(LanguageServer): 60 | def __init__(self, *args, **kwargs): 61 | super().__init__(*args, **kwargs) 62 | self.file_watcher_id = str(uuid.uuid4()) 63 | self.current_file_watcher_globs = [] 64 | self.env_directories = DEFAULT_ENV_DIRECTORIES 65 | self.docker_compose_file = "docker-compose.yml" 66 | self.docker_compose_service = "django" 67 | self.django_settings_module = "" 68 | self.cache = False 69 | self.workspace_index = WorkspaceIndex() 70 | self.workspace_index.update(FALLBACK_DJANGO_DATA) 71 | self.jedi_project = jedi.Project(".") 72 | self.is_initialized = False 73 | 74 | @cached_property 75 | def project_src_path(self): 76 | """Root path to src files, auto detect based on manage.py file""" 77 | for name in os.listdir(self.workspace.root_path): 78 | src_path = os.path.join(self.workspace.root_path, name) 79 | if os.path.exists(os.path.join(src_path, "manage.py")): 80 | return src_path 81 | return self.workspace.root_path 82 | 83 | @cached_property 84 | def project_env_path(self): 85 | for env_dir in self.env_directories: 86 | env_path = ( 87 | env_dir 88 | if os.path.isabs(env_dir) 89 | else os.path.join(self.workspace.root_path, env_dir) 90 | ) 91 | if os.path.exists(os.path.join(env_path, "bin", "python")): 92 | return os.path.join(env_path) 93 | 94 | @property 95 | def docker_compose_path(self): 96 | return os.path.join(self.workspace.root_path, self.docker_compose_file) 97 | 98 | def set_initialization_options(self, options: dict): 99 | env_directories = options.get("env_directories", self.env_directories) 100 | self.env_directories = ( 101 | list(map(str, env_directories)) 102 | if isinstance(env_directories, list) 103 | else self.env_directories 104 | ) 105 | self.docker_compose_file = options.get( 106 | "docker_compose_file", self.docker_compose_file 107 | ) 108 | self.docker_compose_service = options.get( 109 | "docker_compose_service", self.docker_compose_service 110 | ) 111 | self.django_settings_module = options.get( 112 | "django_settings_module", self.django_settings_module 113 | ) 114 | self.cache = options.get("cache", self.cache) 115 | 116 | def check_version(self): 117 | try: 118 | connection = http.client.HTTPSConnection("pypi.org", timeout=1) 119 | connection.request( 120 | "GET", 121 | "/pypi/django-template-lsp/json", 122 | headers={"User-Agent": "Python/3"}, 123 | ) 124 | response = connection.getresponse() 125 | if response.status == 200: 126 | latest_version = ( 127 | json.loads(response.read().decode("utf-8")) 128 | .get("info", {}) 129 | .get("version", "0.0.0") 130 | ) 131 | if self._parse_version(latest_version) > self._parse_version( 132 | __version__ 133 | ): 134 | self.show_message( 135 | f"There is a new version for djlsp ({latest_version})" 136 | ", upgrade with `pipx upgrade django-template-lsp`" 137 | ) 138 | except Exception as e: 139 | logger.error(f"Could not check latest version: {e}") 140 | 141 | def _parse_version(self, version): 142 | # Split the version into major, minor, and patch components 143 | return tuple(map(int, str(version).split("."))) 144 | 145 | def set_file_watcher_capability(self): 146 | logger.info( 147 | f"Update file watcher patterns to: {self.current_file_watcher_globs}" 148 | ) 149 | self.register_capability( 150 | RegistrationParams( 151 | registrations=[ 152 | Registration( 153 | id=self.file_watcher_id, 154 | method=WORKSPACE_DID_CHANGE_WATCHED_FILES, 155 | register_options=DidChangeWatchedFilesRegistrationOptions( 156 | watchers=[ 157 | FileSystemWatcher(glob_pattern=glob_pattern) 158 | for glob_pattern in self.current_file_watcher_globs 159 | ] 160 | ), 161 | ) 162 | ] 163 | ) 164 | ) 165 | 166 | def get_django_data(self, update_file_watcher=True): 167 | self.workspace_index.src_path = self.project_src_path 168 | self.workspace_index.env_path = self.project_env_path 169 | self.jedi_project = jedi.Project( 170 | path=self.project_src_path, environment_path=self.project_env_path 171 | ) 172 | 173 | loaded_from_cache = False 174 | if self.cache and (django_data := self._get_django_data_from_cache()): 175 | loaded_from_cache = True 176 | elif self.project_env_path: 177 | django_data = self._get_django_data_from_python_path( 178 | os.path.join(self.project_env_path, "bin", "python") 179 | ) 180 | elif self._has_valid_docker_service(): 181 | django_data = self._get_django_data_from_docker() 182 | elif python_path := shutil.which("python3"): 183 | # Try getting data with global python installtion 184 | django_data = self._get_django_data_from_python_path(python_path) 185 | else: 186 | django_data = None 187 | 188 | if django_data: 189 | # TODO: Maybe validate data 190 | self.workspace_index.update(django_data) 191 | logger.info("Collected project Django data:") 192 | logger.info(f" - Libraries: {len(django_data['libraries'])}") 193 | logger.info(f" - Templates: {len(django_data['templates'])}") 194 | logger.info(f" - Static files: {len(django_data['static_files'])}") 195 | logger.info(f" - Urls: {len(django_data['urls'])}") 196 | logger.info( 197 | f" - Global context: {len(django_data['global_template_context'])}" 198 | ) 199 | else: 200 | logger.info("Could not collect project Django data") 201 | if not self.is_initialized: 202 | # This message is only shown during startup. On save, a full 203 | # collect occurs, which may involve partial edits. To avoid 204 | # spamming the user with messages, we provide feedback only 205 | # at startup. 206 | self.show_message( 207 | "Failed to collect project-specific Django data. Falling back to default Django completions." # noqa: E501 208 | ) 209 | 210 | if update_file_watcher and set(self.workspace_index.file_watcher_globs) != set( 211 | self.current_file_watcher_globs 212 | ): 213 | self.current_file_watcher_globs = self.workspace_index.file_watcher_globs 214 | self.set_file_watcher_capability() 215 | 216 | if self.cache and not loaded_from_cache and django_data: 217 | self._store_django_data_to_cache(django_data) 218 | 219 | def _get_django_data_from_cache(self): 220 | cache_path = self._get_cache_location() 221 | if not os.path.isfile(cache_path): 222 | return None 223 | 224 | logger.debug(f"Found cachefile: {cache_path}") 225 | try: 226 | with open(cache_path, "r") as f: 227 | django_data = json.load(f) 228 | except Exception: 229 | logger.warning(f"Cannot read cachefile: {cache_path}", exc_info=True) 230 | return None 231 | 232 | prev_hash = django_data.get("_hash", None) 233 | current_hash = self._get_cache_file_hash(django_data) 234 | if prev_hash == current_hash: 235 | logger.info(f"Loaded collected data from cachefile: {cache_path}") 236 | return django_data 237 | else: 238 | logger.debug(f"Cachefile hash does not match {current_hash} != {prev_hash}") 239 | 240 | def _store_django_data_to_cache(self, django_data): 241 | django_data["_hash"] = self._get_cache_file_hash(django_data) 242 | 243 | cache_path = self._get_cache_location() 244 | try: 245 | with open(cache_path, "w") as f: 246 | json.dump(django_data, f) 247 | logger.info(f"Wrote collected data to cachefile: {cache_path}") 248 | except Exception: 249 | logger.warning(f"Cannot write cachefile: {cache_path}", exc_info=True) 250 | 251 | def _get_cache_file_hash(self, django_data): 252 | start_time = time.time() 253 | 254 | patterns = [] 255 | if self.project_env_path and self.project_env_path.startswith( 256 | self.project_src_path 257 | ): 258 | # Prevent using env directory because this increase the calculation 259 | # time by 100x 260 | for file_ in os.scandir(self.project_src_path): 261 | if file_.is_dir(): 262 | full_path = os.path.join(self.project_src_path, file_) 263 | for pattern in django_data.get("file_watcher_globs", []): 264 | if not full_path.startswith(self.project_env_path): 265 | patterns.append(os.path.join(full_path, pattern)) 266 | else: 267 | patterns = list( 268 | [ 269 | os.path.join(self.project_src_path, pattern) 270 | for pattern in django_data.get("file_watcher_globs", []) 271 | ] 272 | ) 273 | 274 | files = set( 275 | file_ 276 | for pattern in patterns 277 | for file_ in glob.iglob(pattern, recursive=True) 278 | ) 279 | files.add(DJANGO_COLLECTOR_SCRIPT_PATH) 280 | 281 | files_hash = hashlib.blake2b(digest_size=16) 282 | for file_path in sorted(files): 283 | if "__pycache__" not in file_path and os.path.isfile(file_path): 284 | files_hash.update(f"{os.stat(file_path).st_mtime}".encode()) 285 | 286 | logger.debug(f"Caculating cache hash took {time.time() - start_time:.4f}s") 287 | 288 | return files_hash.hexdigest() 289 | 290 | def _get_cache_location(self): 291 | if self.cache is True and self.workspace.root_path: 292 | prefix = hashlib.md5(self.workspace.root_path.encode("utf-8")).hexdigest() 293 | return os.path.join(tempfile.gettempdir(), f"djlsp-data-{prefix}.json") 294 | return self.cache 295 | 296 | def _get_django_data_from_python_path(self, python_path): 297 | logger.info(f"Collection django data from local python path: {python_path}") 298 | 299 | command = list( 300 | filter( 301 | None, 302 | [ 303 | python_path, 304 | DJANGO_COLLECTOR_SCRIPT_PATH, 305 | ( 306 | f"--django-settings-module={self.django_settings_module}" # noqa: E501 307 | if self.django_settings_module 308 | else None 309 | ), 310 | f"--project-src={self.project_src_path}", 311 | ], 312 | ) 313 | ) 314 | 315 | logger.debug(f"Collector command: {' '.join(command)}") 316 | 317 | try: 318 | return json.loads(subprocess.check_output(command).decode()) 319 | except Exception: 320 | logger.error("Collector failed with:", exc_info=True) 321 | return False 322 | 323 | def _has_valid_docker_service(self): 324 | if os.path.exists(self.docker_compose_path): 325 | services = ( 326 | subprocess.check_output( 327 | [ 328 | "docker", 329 | "compose", 330 | f"--file={self.docker_compose_path}", 331 | "config", 332 | "--services", 333 | ] 334 | ) 335 | .decode() 336 | .splitlines() 337 | ) 338 | return self.docker_compose_service in services 339 | return False 340 | 341 | def _get_django_data_from_docker(self): 342 | logger.info( 343 | f"Collecting django data from docker {self.docker_compose_file}:{self.docker_compose_service}" # noqa: E501 344 | ) 345 | 346 | docker_image = self._get_docker_image() 347 | if not docker_image: 348 | return False 349 | 350 | docker_run_command = list( 351 | filter( 352 | None, 353 | [ 354 | "docker", 355 | "run", 356 | "--rm", 357 | f"--volume={DJANGO_COLLECTOR_SCRIPT_PATH}:/django-collector.py", 358 | f"--volume={self.project_src_path}:/src", 359 | docker_image, 360 | "python", 361 | "/django-collector.py", 362 | ( 363 | f"--django-settings-module={self.django_settings_module}" 364 | if self.django_settings_module 365 | else None 366 | ), 367 | "--project-src=/src", 368 | ], 369 | ) 370 | ) 371 | 372 | logger.debug(f"Collector command: {' '.join(docker_run_command)}") 373 | 374 | try: 375 | return json.loads(subprocess.check_output(docker_run_command).decode()) 376 | except Exception as e: 377 | logger.error(e) 378 | return False 379 | 380 | def _get_docker_image(self): 381 | try: 382 | # Make sure image is created 383 | subprocess.check_call( 384 | [ 385 | "docker", 386 | "compose", 387 | f"--file={self.docker_compose_path}", 388 | "create", 389 | "--no-recreate", 390 | self.docker_compose_service, 391 | ] 392 | ) 393 | except Exception as e: 394 | logger.error(e) 395 | return None 396 | 397 | try: 398 | images = json.loads( 399 | subprocess.check_output( 400 | [ 401 | "docker", 402 | "compose", 403 | f"--file={self.docker_compose_path}", 404 | "images", 405 | self.docker_compose_service, 406 | "--format=json", 407 | ] 408 | ) 409 | ) 410 | except Exception as e: 411 | logger.error(e) 412 | return None 413 | 414 | if images: 415 | return images[0]["ID"] 416 | return None 417 | 418 | 419 | server = DjangoTemplateLanguageServer("django-template-lsp", __version__) 420 | 421 | 422 | @server.feature(INITIALIZE) 423 | def initialized(ls: DjangoTemplateLanguageServer, params: InitializeParams): 424 | logger.info(f"COMMAND: {INITIALIZE}") 425 | logger.debug(f"OPTIONS: {params.initialization_options}") 426 | if params.initialization_options: 427 | ls.set_initialization_options(params.initialization_options) 428 | ls.check_version() 429 | ls.get_django_data() 430 | ls.is_initialized = True 431 | 432 | 433 | @server.feature( 434 | TEXT_DOCUMENT_COMPLETION, 435 | CompletionOptions( 436 | trigger_characters=[" ", "|", "'", '"', "."], resolve_provider=True 437 | ), 438 | ) 439 | def completions(ls: DjangoTemplateLanguageServer, params: CompletionParams): 440 | logger.info(f"COMMAND: {TEXT_DOCUMENT_COMPLETION}") 441 | logger.debug(f"PARAMS: {params}") 442 | 443 | clear_completions_cache() 444 | try: 445 | return CompletionList( 446 | is_incomplete=False, 447 | items=TemplateParser( 448 | workspace_index=ls.workspace_index, 449 | jedi_project=ls.jedi_project, 450 | document=server.workspace.get_document(params.text_document.uri), 451 | ).completions(params.position.line, params.position.character), 452 | ) 453 | except Exception as e: 454 | logger.error(e) 455 | return None 456 | 457 | 458 | @server.feature(COMPLETION_ITEM_RESOLVE) 459 | def completion_item_resolve(ls: DjangoTemplateLanguageServer, item: CompletionItem): 460 | logger.info(f"COMMAND: {COMPLETION_ITEM_RESOLVE}") 461 | logger.debug(f"PARAMS: {item}") 462 | 463 | return TemplateParser.resolve_completion(item) 464 | 465 | 466 | @server.feature(TEXT_DOCUMENT_HOVER) 467 | def hover(ls: DjangoTemplateLanguageServer, params: HoverParams): 468 | logger.info(f"COMMAND: {TEXT_DOCUMENT_HOVER}") 469 | logger.debug(f"PARAMS: {params}") 470 | try: 471 | return TemplateParser( 472 | workspace_index=ls.workspace_index, 473 | jedi_project=ls.jedi_project, 474 | document=server.workspace.get_document(params.text_document.uri), 475 | ).hover(params.position.line, params.position.character) 476 | except Exception as e: 477 | logger.error(e) 478 | return None 479 | 480 | 481 | @server.feature(TEXT_DOCUMENT_DEFINITION) 482 | def goto_definition(ls: DjangoTemplateLanguageServer, params: DefinitionParams): 483 | logger.info(f"COMMAND: {TEXT_DOCUMENT_DEFINITION}") 484 | logger.debug(f"PARAMS: {params}") 485 | try: 486 | return TemplateParser( 487 | workspace_index=ls.workspace_index, 488 | jedi_project=ls.jedi_project, 489 | document=ls.workspace.get_document(params.text_document.uri), 490 | ).goto_definition(params.position.line, params.position.character) 491 | except Exception as e: 492 | logger.error(e) 493 | return None 494 | 495 | 496 | @server.thread() 497 | @server.feature(WORKSPACE_DID_CHANGE_WATCHED_FILES) 498 | def files_changed( 499 | ls: DjangoTemplateLanguageServer, params: DidChangeWatchedFilesParams 500 | ): 501 | logger.info(f"COMMAND: {WORKSPACE_DID_CHANGE_WATCHED_FILES}") 502 | logger.debug(f"PARAMS: {params}") 503 | # TODO: Do partial collect based on changed file type 504 | ls.get_django_data() 505 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "django-template-lsp" 3 | version = "1.2.0" 4 | description = "Django template LSP" 5 | readme = "README.md" 6 | authors = [{name = "Four Digits", email = "info@fourdigits.nl" }] 7 | license = { file = "LICENSE" } 8 | classifiers = [ 9 | "Environment :: Web Environment", 10 | "Framework :: Django", 11 | "Intended Audience :: Developers", 12 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 13 | "Programming Language :: Python", 14 | "Programming Language :: Python :: 3.9", 15 | "Programming Language :: Python :: 3.10", 16 | "Programming Language :: Python :: 3.11", 17 | "Programming Language :: Python :: 3.12" 18 | ] 19 | keywords = ["django", "template", "lsp", "python"] 20 | dependencies = [ 21 | "pygls", 22 | "jedi" 23 | ] 24 | requires-python = ">=3.9" 25 | 26 | [project.scripts] 27 | djlsp = "djlsp.cli:main" 28 | django-template-lsp = "djlsp.cli:main" 29 | 30 | [project.optional-dependencies] 31 | dev = [ 32 | "tox", 33 | "black", 34 | "isort", 35 | "flake8", 36 | "flake8-pyproject", 37 | "pytest", 38 | "pytest-check", 39 | "pytest-cov", 40 | ] 41 | 42 | [project.urls] 43 | Homepage = "https://github.com/fourdigits/django-template-lsp" 44 | 45 | [build-system] 46 | requires = ["setuptools", "wheel", "build"] 47 | build-backend = "setuptools.build_meta" 48 | 49 | [tool.setuptools] 50 | include-package-data = false 51 | 52 | [tool.setuptools.packages.find] 53 | include = ["djlsp*"] 54 | 55 | [tool.isort] 56 | profile = "black" 57 | known_first_party = "djlsp" 58 | skip_glob = ["tests/django_test/env/*"] 59 | 60 | [tool.flake8] 61 | max-line-length = 88 62 | extend-ignore = "W503" 63 | exclude = "tests/django_test/env/" 64 | -------------------------------------------------------------------------------- /releasing.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | To create a new release, follow these steps: 4 | 5 | - Update the version number in `pyproject.toml` and push this to `main`. 6 | - We use [semantic](https://semver.org/) versioning. 7 | - Create a new tag and push the tag using `git push --tags`. 8 | 9 | The release will be automatically built and published to [PyPi](https://pypi.org/project/django-template-lsp/). 10 | 11 | After publishing to PyPi, a draft release is automatically created on Github. 12 | Edit this release, include the changes in the "What's changed" section and publish the release. 13 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 88 3 | ignore = W503 4 | 5 | [tool:isort] 6 | profile = black 7 | known_first_party = 8 | djlsp 9 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/tests/__init__.py -------------------------------------------------------------------------------- /tests/django_test/.helix/languages.toml: -------------------------------------------------------------------------------- 1 | [language-server.djlsp] 2 | command = "djlsp" 3 | args = ["--enable-log", "--cache"] 4 | 5 | [language-server.djlsp.config] 6 | django_settings_modules="django_test.settings" 7 | 8 | [[language]] 9 | name = "html" 10 | language-servers = [ "djlsp" ] 11 | -------------------------------------------------------------------------------- /tests/django_test/django_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/tests/django_test/django_app/__init__.py -------------------------------------------------------------------------------- /tests/django_test/django_app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DjangoAppConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "django_app" 7 | -------------------------------------------------------------------------------- /tests/django_test/django_app/static/django_app.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/tests/django_test/django_app/static/django_app.js -------------------------------------------------------------------------------- /tests/django_test/django_app/templates/django_app.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/tests/django_test/django_app/templates/django_app.html -------------------------------------------------------------------------------- /tests/django_test/django_app/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/tests/django_test/django_app/templatetags/__init__.py -------------------------------------------------------------------------------- /tests/django_test/django_app/templatetags/django_app.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | 3 | register = template.Library() 4 | 5 | 6 | @register.simple_tag 7 | def django_app_tag(value): 8 | """Docs for tag""" 9 | pass 10 | 11 | 12 | @register.filter 13 | def django_app_filter(value): 14 | """Docs for filter""" 15 | pass 16 | -------------------------------------------------------------------------------- /tests/django_test/django_app/urls.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse 2 | from django.urls import path 3 | 4 | app_name = "django_app" 5 | 6 | 7 | urlpatterns = [ 8 | path("", lambda request: HttpResponse(""), name="index"), 9 | ] 10 | -------------------------------------------------------------------------------- /tests/django_test/django_test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/tests/django_test/django_test/__init__.py -------------------------------------------------------------------------------- /tests/django_test/django_test/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for django_test project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /tests/django_test/django_test/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_test project. 3 | 4 | Generated by 'django-admin startproject' using Django 5.0.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/5.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/5.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = "django-insecure-n)+g*i&2=*)(jr3(4qvtfwu!-c+)n7bub5*#b!ed!208!7%629" 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | "django_app", 35 | "django.contrib.admin", 36 | "django.contrib.auth", 37 | "django.contrib.contenttypes", 38 | "django.contrib.sessions", 39 | "django.contrib.messages", 40 | "django.contrib.staticfiles", 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | "django.middleware.security.SecurityMiddleware", 45 | "django.contrib.sessions.middleware.SessionMiddleware", 46 | "django.middleware.common.CommonMiddleware", 47 | "django.middleware.csrf.CsrfViewMiddleware", 48 | "django.contrib.auth.middleware.AuthenticationMiddleware", 49 | "django.contrib.messages.middleware.MessageMiddleware", 50 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 51 | ] 52 | 53 | ROOT_URLCONF = "django_test.urls" 54 | 55 | TEMPLATES = [ 56 | { 57 | "BACKEND": "django.template.backends.django.DjangoTemplates", 58 | "DIRS": [ 59 | BASE_DIR / "test-templates-folder", 60 | ], 61 | "APP_DIRS": True, 62 | "OPTIONS": { 63 | "context_processors": [ 64 | "django.template.context_processors.debug", 65 | "django.template.context_processors.request", 66 | "django.contrib.auth.context_processors.auth", 67 | "django.contrib.messages.context_processors.messages", 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = "django_test.wsgi.application" 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/5.0/ref/settings/#databases 78 | 79 | DATABASES = { 80 | "default": { 81 | "ENGINE": "django.db.backends.sqlite3", 82 | "NAME": BASE_DIR / "db.sqlite3", 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", # noqa: E501 93 | }, 94 | { 95 | "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", 96 | }, 97 | { 98 | "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", 99 | }, 100 | { 101 | "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/5.0/topics/i18n/ 108 | 109 | LANGUAGE_CODE = "en-us" 110 | 111 | TIME_ZONE = "UTC" 112 | 113 | USE_I18N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/5.0/howto/static-files/ 120 | 121 | STATIC_URL = "static/" 122 | 123 | STATICFILES_DIRS = [ 124 | BASE_DIR / "test-static-folder", 125 | ] 126 | 127 | # Default primary key field type 128 | # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field 129 | 130 | DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" 131 | -------------------------------------------------------------------------------- /tests/django_test/django_test/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import include, path 2 | 3 | urlpatterns = [path("", include("django_app.urls", namespace="django_app"))] 4 | -------------------------------------------------------------------------------- /tests/django_test/django_test/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_test project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tests/django_test/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /tests/django_test/test-static-folder/.gitkeep: -------------------------------------------------------------------------------- 1 | Needed for django 3.2 2 | -------------------------------------------------------------------------------- /tests/test_completion_kinds.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test the type of completion feedback returned by diagnostic server, such as 3 | properties, methods and keywords 4 | """ 5 | 6 | import pytest 7 | from lsprotocol.types import CompletionItemKind 8 | 9 | from tests.test_parser import create_parser 10 | 11 | 12 | @pytest.mark.parametrize( 13 | "content,line_number,expected_kind", 14 | [ 15 | ("{# type blog: django", 0, CompletionItemKind.Module), 16 | ("{% load website %}\n{{ value|up", 1, CompletionItemKind.Function), 17 | ("{% url 'web", 0, CompletionItemKind.Reference), 18 | ("{% static 'js", 0, CompletionItemKind.File), 19 | ("{{ bl", 0, CompletionItemKind.Variable), 20 | ("{# type news: str #}\n{{ news|cap", 1, CompletionItemKind.Function), 21 | ("{% extends 'ba", 0, CompletionItemKind.File), 22 | ("{% block header %}\n{% endblock ", 1, CompletionItemKind.Property), 23 | ("{% load w", 0, CompletionItemKind.Module), 24 | ("{% extends 'base.html' %}\n{% block h", 1, CompletionItemKind.Property), 25 | ( 26 | "{# type customer: django.db.models.Model #}\n{{ customer.sav", 27 | 1, 28 | CompletionItemKind.Function, 29 | ), 30 | ( 31 | "{# type customer: django.db.models.Model #}\n{{ customer.objec", 32 | 1, 33 | CompletionItemKind.Module, 34 | ), 35 | ( 36 | "{# type customer: django.db.models.Model #}\n{{ customer.pk", 37 | 1, 38 | CompletionItemKind.Variable, 39 | ), 40 | ], 41 | ) 42 | def test_completion_suggestion_kind( 43 | content: str, line_number: int, expected_kind: CompletionItemKind 44 | ): 45 | parser = create_parser(content) 46 | 47 | lines = content.split("\n") 48 | target_line = lines[line_number] 49 | eol = len(target_line) 50 | 51 | completions = parser.completions(line_number, eol) 52 | assert completions 53 | assert completions[0].kind == expected_kind 54 | -------------------------------------------------------------------------------- /tests/test_django_collector.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import shutil 4 | import subprocess 5 | 6 | from djlsp.index import WorkspaceIndex 7 | from djlsp.server import DJANGO_COLLECTOR_SCRIPT_PATH 8 | 9 | DJANGO_TEST_PROJECT_SRC = os.path.join( 10 | os.path.dirname(os.path.realpath(__file__)), 11 | "django_test", 12 | ) 13 | DJANGO_TEST_SETTINGS_MODULE = "django_test.settings" 14 | 15 | 16 | def test_django_collect(): 17 | django_data = json.loads( 18 | subprocess.check_output( 19 | [ 20 | shutil.which("python"), # Get tox python path 21 | DJANGO_COLLECTOR_SCRIPT_PATH, 22 | f"--django-settings-module={DJANGO_TEST_SETTINGS_MODULE}", 23 | f"--project-src={DJANGO_TEST_PROJECT_SRC}", 24 | ] 25 | ) 26 | ) 27 | 28 | index = WorkspaceIndex() 29 | index.update(django_data) 30 | 31 | assert "django_app_tag" in index.libraries["django_app"].tags 32 | assert index.libraries["django_app"].tags["django_app_tag"].docs == "Docs for tag" 33 | 34 | assert "django_app_filter" in index.libraries["django_app"].filters 35 | assert ( 36 | index.libraries["django_app"].filters["django_app_filter"].docs 37 | == "Docs for filter" 38 | ) 39 | 40 | assert "django_app.html" in index.templates 41 | assert ( 42 | index.templates["django_app.html"].path 43 | == "src:django_app/templates/django_app.html" 44 | ) 45 | 46 | assert "django_app.js" in index.static_files 47 | assert "django_app:index" in index.urls 48 | assert set(index.file_watcher_globs) == { 49 | "**/templates/**", 50 | "**/templatetags/**", 51 | "**/static/**", 52 | "**/test-templates-folder/**", 53 | "**/test-static-folder/**", 54 | } 55 | -------------------------------------------------------------------------------- /tests/test_parser.py: -------------------------------------------------------------------------------- 1 | import jedi 2 | import pytest 3 | from pygls.workspace import TextDocument 4 | 5 | from djlsp.constants import FALLBACK_DJANGO_DATA 6 | from djlsp.index import WorkspaceIndex 7 | from djlsp.parser import TemplateParser 8 | 9 | 10 | def create_parser(source) -> TemplateParser: 11 | workspace_index = WorkspaceIndex(src_path="/project/src", env_path="/project/env") 12 | workspace_index.update( 13 | { 14 | "static_files": ["js/main.js", "css/main.css"], 15 | "urls": { 16 | "website:home": { 17 | "docs": "Homepage", 18 | "source": "src:views.py:12", 19 | }, 20 | "blog:list": { 21 | "docs": "Blog list", 22 | "source": "src:views.py:22", 23 | }, 24 | "blog:detail": { 25 | "docs": "Blog detail", 26 | "source": "src:views.py:32", 27 | }, 28 | }, 29 | "libraries": { 30 | "__builtins__": FALLBACK_DJANGO_DATA["libraries"]["__builtins__"], 31 | "website": { 32 | "tags": { 33 | "get_homepage": { 34 | "name": "get_homepage", 35 | "docs": "Retrieve the homepage.", 36 | "source": "src:templatetags/website.py:8", 37 | }, 38 | }, 39 | "filters": { 40 | "currency": { 41 | "name": "currency", 42 | "docs": "Formats a number as currency.", 43 | "source": "src:filters.py:5", 44 | }, 45 | }, 46 | }, 47 | }, 48 | "templates": { 49 | "base.html": { 50 | "path": "src:templates/base.html", 51 | "blocks": ["header", "content"], 52 | }, 53 | "blog/list.html": { 54 | "path": "src:templates/blog/list.html", 55 | "extends": "base.html", 56 | "context": { 57 | "blog": { 58 | "type": "list[str]", 59 | "docs": "This is a doc for the blog context variable", 60 | } 61 | }, 62 | }, 63 | }, 64 | } 65 | ) 66 | 67 | return TemplateParser( 68 | workspace_index=workspace_index, 69 | jedi_project=jedi.Project("."), 70 | document=TextDocument( 71 | uri="file:///templates/blog/list.html", 72 | source=source, 73 | ), 74 | ) 75 | 76 | 77 | ################################################################################### 78 | # Completions 79 | ################################################################################### 80 | def test_completion_load(): 81 | parser = create_parser("{% load w") 82 | assert any(item.label == "website" for item in parser.completions(0, 8)) 83 | 84 | 85 | def test_completion_block(): 86 | parser = create_parser("{% extends 'base.html' %}\n{% block h}") 87 | assert any(item.label == "header" for item in parser.completions(1, 9)) 88 | 89 | 90 | def test_completion_block_no_used_block(): 91 | parser = create_parser( 92 | "{% extends 'base.html' %}\n{% block header %}{% endblock }%\n{% block h}" 93 | ) 94 | assert not any(item.label == "header" for item in parser.completions(2, 9)) 95 | 96 | 97 | def test_completion_endblock(): 98 | parser = create_parser("{% block new %}\n{% endblock ") 99 | assert any(item.label == "new" for item in parser.completions(1, 12)) 100 | 101 | 102 | def test_completion_url(): 103 | parser = create_parser("{% url 'bl") 104 | assert any(item.label == "website:home" for item in parser.completions(0, 8)) 105 | items = parser.completions(0, 9) 106 | assert items 107 | assert all(item.label.startswith("blog") for item in items) 108 | 109 | 110 | def test_completion_static(): 111 | parser = create_parser("{% static 'js") 112 | assert any(item.label == "js/main.js" for item in parser.completions(0, 12)) 113 | items = parser.completions(0, 14) 114 | assert items 115 | assert all(item.label.startswith("js") for item in items) 116 | 117 | 118 | def test_completion_templates_extends(): 119 | parser = create_parser("{% extends 'ba") 120 | assert any(item.label == "blog/list.html" for item in parser.completions(0, 12)) 121 | items = parser.completions(0, 14) 122 | assert items 123 | assert all(item.label.startswith("ba") for item in items) 124 | 125 | 126 | def test_completion_templates_include(): 127 | parser = create_parser("{% include 'ba") 128 | assert any(item.label == "blog/list.html" for item in parser.completions(0, 12)) 129 | items = parser.completions(0, 14) 130 | assert items 131 | assert all(item.label.startswith("ba") for item in items) 132 | 133 | 134 | def test_completion_tags_builtins(): 135 | parser = create_parser("{% url") 136 | assert any(item.label == "load" for item in parser.completions(0, 2)) 137 | items = parser.completions(0, 4) 138 | assert items 139 | assert all([item.label.startswith("ur") for item in items]) 140 | 141 | 142 | def test_completion_tags_missing_load(): 143 | parser = create_parser("{% ") 144 | assert not any(item.label == "get_homepage" for item in parser.completions(0, 2)) 145 | 146 | 147 | def test_completion_tags(): 148 | parser = create_parser("{% load website %}\n{% ") 149 | assert any(item.label == "get_homepage" for item in parser.completions(1, 2)) 150 | 151 | 152 | def test_completion_filter(): 153 | parser = create_parser("{% load website %}\n{{some|cur}}") 154 | assert any(item.label == "currency" for item in parser.completions(1, 10)) 155 | 156 | 157 | def test_completion_filter_missing_load(): 158 | parser = create_parser("{{some|cur}}") 159 | assert not any(item.label == "currency" for item in parser.completions(0, 10)) 160 | 161 | 162 | def test_completion_comment(): 163 | parser = create_parser("{# type blog: dj }") 164 | assert any(item.label == "djlsp" for item in parser.completions(0, 16)) 165 | 166 | 167 | def test_completion_context(): 168 | parser = create_parser("{{ bl") 169 | assert any(item.label == "blog" for item in parser.completions(0, 5)) 170 | 171 | 172 | @pytest.mark.parametrize( 173 | "content,results", 174 | [ 175 | ("{% if ", True), 176 | ("{% endif ", False), 177 | ("{% comment ", False), 178 | ("{% csrf_token ", False), 179 | ("{% debug ", False), 180 | ("{% spaceless ", False), 181 | ], 182 | ) 183 | def test_no_completion_context_for_some_tags(content, results): 184 | parser = create_parser(content) 185 | assert bool(parser.completions(0, len(content))) is results 186 | 187 | 188 | def test_completion_context_based_type_hint_comment(): 189 | parser = create_parser("{# type news: str #}\n{{ news.cap") 190 | assert any(item.label == "news" for item in parser.completions(1, 5)) 191 | assert any(item.label == "capitalize" for item in parser.completions(1, 10)) 192 | 193 | 194 | def test_completion_context_with_same_symbol_name(): 195 | parser = create_parser("{# type jedi: jedi.Script #}\n{{ jedi.com") 196 | assert any(item.label == "complete" for item in parser.completions(1, 10)) 197 | 198 | 199 | @pytest.mark.parametrize( 200 | "code,cursor,result,detail,doc", 201 | [ 202 | ( 203 | "{# type abc: list[str] #}\n{{ abc.0.", 204 | (1, 9), 205 | "capitalize", 206 | "(function) capitalize", 207 | "capitalize() -> str\n\nReturn a capitalized version of the string.", 208 | ), 209 | ( 210 | "{# type abc: list[jedi.Script] | dict[str, jedi.Script] #}\n{{ abc.0.", 211 | (1, 9), 212 | "complete", 213 | "(function) complete", 214 | "", 215 | ), 216 | ( 217 | "{{ blo", 218 | (0, 6), 219 | "blog", 220 | "blog: list[str]", 221 | "This is a doc for the blog context variable", 222 | ), 223 | ( 224 | "{# type test_dict: dict[str, str] #}\n" 225 | "{% for k, v in test_dict.items %}\n{{ k.", 226 | (2, 5), 227 | "capitalize", 228 | "(function) capitalize", 229 | "", 230 | ), 231 | ], 232 | ) 233 | def test_completion_context_advanced(code, cursor, result, detail, doc): 234 | parser = create_parser(code) 235 | found = False 236 | for item in parser.completions(*cursor): 237 | item = parser.resolve_completion(item) 238 | if ( 239 | item.label == result 240 | and item.detail == detail 241 | and item.documentation.startswith(doc) 242 | ): 243 | found = True 244 | break 245 | 246 | assert found 247 | 248 | 249 | def test_completion_context_scoped(): 250 | base = "\n".join( 251 | [ 252 | "{# type test_dict: dict[str, list[str]] #}", 253 | "{% with test_dict_alias=test_dict%}", 254 | " {% for a in test_dict_alias %}", 255 | " {% for k,v in test_dict.items %}", 256 | " {% for e in v %}", 257 | " {{ e }}", 258 | " {% endfor %}", 259 | "", 260 | " {% for world in v %}", 261 | "{{ ", 262 | ] 263 | ) 264 | completed_base = ( 265 | base + " world }}\n{% endfor %}\n{% endfor %}\n{% endfor %}\n{% endwith %}" 266 | ) 267 | 268 | assert not any( 269 | item.label == "e" for item in create_parser(base).completions(9, 3) 270 | ), "do not recommend out of scope variables" 271 | assert not any( 272 | item.label == "forloop" 273 | for item in create_parser(completed_base + "\n{{ ").completions(14, 3) 274 | ), "do not complete for loop outside of foor loop" 275 | assert any( 276 | item.label == "capitalize" 277 | for item in create_parser(base + "world.").completions(9, 9) 278 | ), "recommend correct variables for scope and support intelisense" 279 | assert any( 280 | item.label == "forloop" for item in create_parser(base).completions(9, 3) 281 | ), "test that django forloop variable is precense in foor loop" 282 | 283 | 284 | ################################################################################### 285 | # Hovers 286 | ################################################################################### 287 | def test_hover_url(): 288 | parser = create_parser("{% url 'website:home' %}") 289 | hover = parser.hover(0, 12) 290 | assert hover is not None 291 | assert hover.contents == "Homepage" 292 | 293 | 294 | def test_hover_filter(): 295 | parser = create_parser("{% load website %}\n{{ some_variable|currency }}") 296 | hover = parser.hover(1, 23) 297 | assert hover is not None 298 | assert hover.contents == "Formats a number as currency." 299 | 300 | 301 | def test_hover_tag(): 302 | parser = create_parser("{% load website %}\n{% get_homepage %}") 303 | hover = parser.hover(1, 12) 304 | assert hover is not None 305 | assert hover.contents == "Retrieve the homepage." 306 | 307 | 308 | def test_hover_context(): 309 | parser = create_parser("{# type news: str #}\n{{ news }}") 310 | hover = parser.hover(1, 4) 311 | assert hover is not None 312 | assert hover.contents == "(variable) news: str" 313 | 314 | 315 | def test_hover_context_docs(): 316 | parser = create_parser("{{ blog }}") 317 | hover = parser.hover(0, 4) 318 | assert hover is not None 319 | assert ( 320 | hover.contents 321 | == "(variable) blog: list[str]\n\nThis is a doc for the blog context variable" 322 | ) 323 | 324 | 325 | def test_hover_context_function(): 326 | parser = create_parser("{# type test_str: str #}\n{{ test_str.capitalize") 327 | hover = parser.hover(1, 17) 328 | assert hover is not None 329 | assert hover.contents.startswith("(function) capitalize: capitalize(self) -> str") 330 | 331 | 332 | def test_hover_context_forloop(): 333 | parser = create_parser("{# type test_str: list[str] #}\n{% for abc in test_str %}") 334 | hover = parser.hover(1, 9) 335 | assert hover is not None 336 | assert hover.contents == "(statement) abc: str" 337 | 338 | 339 | ################################################################################### 340 | # Goto Definitions 341 | ################################################################################### 342 | def test_goto_definition_url(): 343 | parser = create_parser("{% url 'website:home' %}") 344 | definition = parser.goto_definition(0, 12) 345 | assert definition is not None 346 | assert definition.uri == "file:///project/src/views.py" 347 | assert definition.range.start.line == 12 348 | assert definition.range.start.character == 0 349 | 350 | 351 | def test_goto_definition_filter(): 352 | parser = create_parser("{% load website %}\n{{ some_variable|currency }}") 353 | definition = parser.goto_definition(1, 25) 354 | assert definition is not None 355 | assert definition.uri == "file:///project/src/filters.py" 356 | assert definition.range.start.line == 5 357 | assert definition.range.start.character == 0 358 | 359 | 360 | def test_goto_definition_tag(): 361 | parser = create_parser("{% load website %}\n{% get_homepage %}") 362 | definition = parser.goto_definition(1, 14) 363 | assert definition is not None 364 | assert definition.uri == "file:///project/src/templatetags/website.py" 365 | assert definition.range.start.line == 8 366 | assert definition.range.start.character == 0 367 | 368 | 369 | @pytest.mark.parametrize( 370 | "content", 371 | [ 372 | """{% extends 'base.html' %}""", 373 | """{% extends "base.html" %}""", 374 | """{% include 'base.html' %}""", 375 | """{% include "base.html" %}""", 376 | ], 377 | ) 378 | def test_goto_definition_template(content): 379 | parser = create_parser(content) 380 | definition = parser.goto_definition(0, 16) 381 | assert definition is not None 382 | assert definition.uri == "file:///project/src/templates/base.html" 383 | assert definition.range.start.line == 0 384 | assert definition.range.start.character == 0 385 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | django42 4 | django50 5 | django51 6 | django52 7 | 8 | [testenv] 9 | commands = 10 | pytest -vv --cov=djlsp --cov-report=html --cov-report=term 11 | 12 | deps = 13 | .[dev] 14 | django42: django==4.2.* 15 | django50: django==5.0.* 16 | django51: django==5.1.* 17 | django52: django==5.2.* 18 | 19 | 20 | [pytest] 21 | testpaths = 22 | tests 23 | -------------------------------------------------------------------------------- /vscode/.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | client/node_modules/** 3 | client/out/** 4 | server/node_modules/** 5 | server/out/** 6 | -------------------------------------------------------------------------------- /vscode/.eslintrc.js: -------------------------------------------------------------------------------- 1 | /**@type {import('eslint').Linter.Config} */ 2 | // eslint-disable-next-line no-undef 3 | module.exports = { 4 | root: true, 5 | parser: '@typescript-eslint/parser', 6 | plugins: [ 7 | '@typescript-eslint', 8 | ], 9 | extends: [ 10 | 'eslint:recommended', 11 | 'plugin:@typescript-eslint/recommended', 12 | ], 13 | rules: { 14 | 'semi': [2, "always"], 15 | '@typescript-eslint/no-unused-vars': 0, 16 | '@typescript-eslint/no-explicit-any': 0, 17 | '@typescript-eslint/explicit-module-boundary-types': 0, 18 | '@typescript-eslint/no-non-null-assertion': 0, 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /vscode/.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | node_modules 3 | client/server 4 | .vscode-test 5 | djlsp.vsix 6 | -------------------------------------------------------------------------------- /vscode/.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | **/*.ts 3 | **/*.map 4 | .gitignore 5 | **/tsconfig.json 6 | **/tsconfig.base.json 7 | contributing.md 8 | .travis.yml 9 | client/node_modules/** 10 | !client/node_modules/vscode-jsonrpc/** 11 | !client/node_modules/vscode-languageclient/** 12 | !client/node_modules/vscode-languageserver-protocol/** 13 | !client/node_modules/vscode-languageserver-types/** 14 | !client/node_modules/{minimatch,brace-expansion,concat-map,balanced-match}/** 15 | !client/node_modules/{semver,lru-cache,yallist}/** 16 | -------------------------------------------------------------------------------- /vscode/README.md: -------------------------------------------------------------------------------- 1 | # Django Template LSP vscode extension 2 | 3 | This extension provides Django Template Language completions for Visual Studio Code. 4 | 5 | ## Usage 6 | 7 | Make sure you have installed the python `django-template-lsp` package on your system. You can install it using pipx: 8 | 9 | ```bash 10 | pipx install django-template-lsp 11 | ``` 12 | 13 | Then, install the `djlsp` extension from the Visual Studio Code marketplace. 14 | 15 | 16 | ## Settings 17 | 18 | Within the `settings.json` file, you can configure the following settings: 19 | - `djangoTemplateLsp.djlspPath`: Path to the `djlsp` executable. When empty it will look for djlsp in your ~/.local/ directory Default: `` 20 | - `djangoTemplateLsp.dockerComposeFile`: Docker Compose file name. Default: `docker-compose.yml` 21 | - `djangoTemplateLsp.dockerServiceName`: Docker service name. Default: `django` 22 | - `djangoTemplateLsp.djangoSettingsModule`: Django settings module. Default: `` 23 | - `djangoTemplateLsp.enableLogging`: Enable logging. Default: `false` 24 | 25 | -------------------------------------------------------------------------------- /vscode/RELEASE.md: -------------------------------------------------------------------------------- 1 | # How to release this package. 2 | 3 | - 1. Update the version number in `vscode/package.json` 4 | - 2. Run the following commands from the `vscode` directory: 5 | ```bash 6 | npm install 7 | npm run compile 8 | npm run vsce-package 9 | ``` 10 | - 3. Upload the generated `.vsix` file to the [Visual Studio Code Marketplace](https://marketplace.visualstudio.com/manage/publishers/fourdigits) 11 | 12 | -------------------------------------------------------------------------------- /vscode/client/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "djlsp-client", 3 | "version": "0.0.1", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "djlsp-client", 9 | "version": "0.0.1", 10 | "license": "MIT", 11 | "dependencies": { 12 | "vscode-languageclient": "^9.0.1" 13 | }, 14 | "devDependencies": { 15 | "@types/vscode": "^1.75.1", 16 | "@vscode/test-electron": "^2.3.9" 17 | }, 18 | "engines": { 19 | "vscode": "^1.75.0" 20 | } 21 | }, 22 | "node_modules/@types/vscode": { 23 | "version": "1.89.0", 24 | "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.89.0.tgz", 25 | "integrity": "sha512-TMfGKLSVxfGfoO8JfIE/neZqv7QLwS4nwPwL/NwMvxtAY2230H2I4Z5xx6836pmJvMAzqooRQ4pmLm7RUicP3A==", 26 | "dev": true 27 | }, 28 | "node_modules/@vscode/test-electron": { 29 | "version": "2.4.0", 30 | "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.4.0.tgz", 31 | "integrity": "sha512-yojuDFEjohx6Jb+x949JRNtSn6Wk2FAh4MldLE3ck9cfvCqzwxF32QsNy1T9Oe4oT+ZfFcg0uPUCajJzOmPlTA==", 32 | "dev": true, 33 | "dependencies": { 34 | "http-proxy-agent": "^7.0.2", 35 | "https-proxy-agent": "^7.0.4", 36 | "jszip": "^3.10.1", 37 | "ora": "^7.0.1", 38 | "semver": "^7.6.2" 39 | }, 40 | "engines": { 41 | "node": ">=16" 42 | } 43 | }, 44 | "node_modules/agent-base": { 45 | "version": "7.1.1", 46 | "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", 47 | "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", 48 | "dev": true, 49 | "dependencies": { 50 | "debug": "^4.3.4" 51 | }, 52 | "engines": { 53 | "node": ">= 14" 54 | } 55 | }, 56 | "node_modules/ansi-regex": { 57 | "version": "6.0.1", 58 | "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", 59 | "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", 60 | "dev": true, 61 | "engines": { 62 | "node": ">=12" 63 | }, 64 | "funding": { 65 | "url": "https://github.com/chalk/ansi-regex?sponsor=1" 66 | } 67 | }, 68 | "node_modules/balanced-match": { 69 | "version": "1.0.2", 70 | "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", 71 | "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" 72 | }, 73 | "node_modules/base64-js": { 74 | "version": "1.5.1", 75 | "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", 76 | "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", 77 | "dev": true, 78 | "funding": [ 79 | { 80 | "type": "github", 81 | "url": "https://github.com/sponsors/feross" 82 | }, 83 | { 84 | "type": "patreon", 85 | "url": "https://www.patreon.com/feross" 86 | }, 87 | { 88 | "type": "consulting", 89 | "url": "https://feross.org/support" 90 | } 91 | ] 92 | }, 93 | "node_modules/bl": { 94 | "version": "5.1.0", 95 | "resolved": "https://registry.npmjs.org/bl/-/bl-5.1.0.tgz", 96 | "integrity": "sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ==", 97 | "dev": true, 98 | "dependencies": { 99 | "buffer": "^6.0.3", 100 | "inherits": "^2.0.4", 101 | "readable-stream": "^3.4.0" 102 | } 103 | }, 104 | "node_modules/bl/node_modules/readable-stream": { 105 | "version": "3.6.2", 106 | "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", 107 | "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", 108 | "dev": true, 109 | "dependencies": { 110 | "inherits": "^2.0.3", 111 | "string_decoder": "^1.1.1", 112 | "util-deprecate": "^1.0.1" 113 | }, 114 | "engines": { 115 | "node": ">= 6" 116 | } 117 | }, 118 | "node_modules/brace-expansion": { 119 | "version": "2.0.1", 120 | "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", 121 | "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", 122 | "dependencies": { 123 | "balanced-match": "^1.0.0" 124 | } 125 | }, 126 | "node_modules/buffer": { 127 | "version": "6.0.3", 128 | "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", 129 | "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", 130 | "dev": true, 131 | "funding": [ 132 | { 133 | "type": "github", 134 | "url": "https://github.com/sponsors/feross" 135 | }, 136 | { 137 | "type": "patreon", 138 | "url": "https://www.patreon.com/feross" 139 | }, 140 | { 141 | "type": "consulting", 142 | "url": "https://feross.org/support" 143 | } 144 | ], 145 | "dependencies": { 146 | "base64-js": "^1.3.1", 147 | "ieee754": "^1.2.1" 148 | } 149 | }, 150 | "node_modules/chalk": { 151 | "version": "5.3.0", 152 | "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", 153 | "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", 154 | "dev": true, 155 | "engines": { 156 | "node": "^12.17.0 || ^14.13 || >=16.0.0" 157 | }, 158 | "funding": { 159 | "url": "https://github.com/chalk/chalk?sponsor=1" 160 | } 161 | }, 162 | "node_modules/cli-cursor": { 163 | "version": "4.0.0", 164 | "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", 165 | "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", 166 | "dev": true, 167 | "dependencies": { 168 | "restore-cursor": "^4.0.0" 169 | }, 170 | "engines": { 171 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 172 | }, 173 | "funding": { 174 | "url": "https://github.com/sponsors/sindresorhus" 175 | } 176 | }, 177 | "node_modules/cli-spinners": { 178 | "version": "2.9.2", 179 | "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", 180 | "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", 181 | "dev": true, 182 | "engines": { 183 | "node": ">=6" 184 | }, 185 | "funding": { 186 | "url": "https://github.com/sponsors/sindresorhus" 187 | } 188 | }, 189 | "node_modules/core-util-is": { 190 | "version": "1.0.3", 191 | "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", 192 | "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", 193 | "dev": true 194 | }, 195 | "node_modules/debug": { 196 | "version": "4.3.5", 197 | "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", 198 | "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", 199 | "dev": true, 200 | "dependencies": { 201 | "ms": "2.1.2" 202 | }, 203 | "engines": { 204 | "node": ">=6.0" 205 | }, 206 | "peerDependenciesMeta": { 207 | "supports-color": { 208 | "optional": true 209 | } 210 | } 211 | }, 212 | "node_modules/eastasianwidth": { 213 | "version": "0.2.0", 214 | "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", 215 | "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", 216 | "dev": true 217 | }, 218 | "node_modules/emoji-regex": { 219 | "version": "10.3.0", 220 | "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", 221 | "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", 222 | "dev": true 223 | }, 224 | "node_modules/http-proxy-agent": { 225 | "version": "7.0.2", 226 | "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", 227 | "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", 228 | "dev": true, 229 | "dependencies": { 230 | "agent-base": "^7.1.0", 231 | "debug": "^4.3.4" 232 | }, 233 | "engines": { 234 | "node": ">= 14" 235 | } 236 | }, 237 | "node_modules/https-proxy-agent": { 238 | "version": "7.0.4", 239 | "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.4.tgz", 240 | "integrity": "sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==", 241 | "dev": true, 242 | "dependencies": { 243 | "agent-base": "^7.0.2", 244 | "debug": "4" 245 | }, 246 | "engines": { 247 | "node": ">= 14" 248 | } 249 | }, 250 | "node_modules/ieee754": { 251 | "version": "1.2.1", 252 | "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", 253 | "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", 254 | "dev": true, 255 | "funding": [ 256 | { 257 | "type": "github", 258 | "url": "https://github.com/sponsors/feross" 259 | }, 260 | { 261 | "type": "patreon", 262 | "url": "https://www.patreon.com/feross" 263 | }, 264 | { 265 | "type": "consulting", 266 | "url": "https://feross.org/support" 267 | } 268 | ] 269 | }, 270 | "node_modules/immediate": { 271 | "version": "3.0.6", 272 | "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", 273 | "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", 274 | "dev": true 275 | }, 276 | "node_modules/inherits": { 277 | "version": "2.0.4", 278 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", 279 | "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", 280 | "dev": true 281 | }, 282 | "node_modules/is-interactive": { 283 | "version": "2.0.0", 284 | "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", 285 | "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", 286 | "dev": true, 287 | "engines": { 288 | "node": ">=12" 289 | }, 290 | "funding": { 291 | "url": "https://github.com/sponsors/sindresorhus" 292 | } 293 | }, 294 | "node_modules/is-unicode-supported": { 295 | "version": "1.3.0", 296 | "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", 297 | "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", 298 | "dev": true, 299 | "engines": { 300 | "node": ">=12" 301 | }, 302 | "funding": { 303 | "url": "https://github.com/sponsors/sindresorhus" 304 | } 305 | }, 306 | "node_modules/isarray": { 307 | "version": "1.0.0", 308 | "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", 309 | "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", 310 | "dev": true 311 | }, 312 | "node_modules/jszip": { 313 | "version": "3.10.1", 314 | "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", 315 | "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", 316 | "dev": true, 317 | "dependencies": { 318 | "lie": "~3.3.0", 319 | "pako": "~1.0.2", 320 | "readable-stream": "~2.3.6", 321 | "setimmediate": "^1.0.5" 322 | } 323 | }, 324 | "node_modules/lie": { 325 | "version": "3.3.0", 326 | "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", 327 | "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", 328 | "dev": true, 329 | "dependencies": { 330 | "immediate": "~3.0.5" 331 | } 332 | }, 333 | "node_modules/log-symbols": { 334 | "version": "5.1.0", 335 | "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-5.1.0.tgz", 336 | "integrity": "sha512-l0x2DvrW294C9uDCoQe1VSU4gf529FkSZ6leBl4TiqZH/e+0R7hSfHQBNut2mNygDgHwvYHfFLn6Oxb3VWj2rA==", 337 | "dev": true, 338 | "dependencies": { 339 | "chalk": "^5.0.0", 340 | "is-unicode-supported": "^1.1.0" 341 | }, 342 | "engines": { 343 | "node": ">=12" 344 | }, 345 | "funding": { 346 | "url": "https://github.com/sponsors/sindresorhus" 347 | } 348 | }, 349 | "node_modules/mimic-fn": { 350 | "version": "2.1.0", 351 | "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", 352 | "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", 353 | "dev": true, 354 | "engines": { 355 | "node": ">=6" 356 | } 357 | }, 358 | "node_modules/minimatch": { 359 | "version": "5.1.6", 360 | "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", 361 | "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", 362 | "dependencies": { 363 | "brace-expansion": "^2.0.1" 364 | }, 365 | "engines": { 366 | "node": ">=10" 367 | } 368 | }, 369 | "node_modules/ms": { 370 | "version": "2.1.2", 371 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", 372 | "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", 373 | "dev": true 374 | }, 375 | "node_modules/onetime": { 376 | "version": "5.1.2", 377 | "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", 378 | "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", 379 | "dev": true, 380 | "dependencies": { 381 | "mimic-fn": "^2.1.0" 382 | }, 383 | "engines": { 384 | "node": ">=6" 385 | }, 386 | "funding": { 387 | "url": "https://github.com/sponsors/sindresorhus" 388 | } 389 | }, 390 | "node_modules/ora": { 391 | "version": "7.0.1", 392 | "resolved": "https://registry.npmjs.org/ora/-/ora-7.0.1.tgz", 393 | "integrity": "sha512-0TUxTiFJWv+JnjWm4o9yvuskpEJLXTcng8MJuKd+SzAzp2o+OP3HWqNhB4OdJRt1Vsd9/mR0oyaEYlOnL7XIRw==", 394 | "dev": true, 395 | "dependencies": { 396 | "chalk": "^5.3.0", 397 | "cli-cursor": "^4.0.0", 398 | "cli-spinners": "^2.9.0", 399 | "is-interactive": "^2.0.0", 400 | "is-unicode-supported": "^1.3.0", 401 | "log-symbols": "^5.1.0", 402 | "stdin-discarder": "^0.1.0", 403 | "string-width": "^6.1.0", 404 | "strip-ansi": "^7.1.0" 405 | }, 406 | "engines": { 407 | "node": ">=16" 408 | }, 409 | "funding": { 410 | "url": "https://github.com/sponsors/sindresorhus" 411 | } 412 | }, 413 | "node_modules/pako": { 414 | "version": "1.0.11", 415 | "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", 416 | "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", 417 | "dev": true 418 | }, 419 | "node_modules/process-nextick-args": { 420 | "version": "2.0.1", 421 | "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", 422 | "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", 423 | "dev": true 424 | }, 425 | "node_modules/readable-stream": { 426 | "version": "2.3.8", 427 | "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", 428 | "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", 429 | "dev": true, 430 | "dependencies": { 431 | "core-util-is": "~1.0.0", 432 | "inherits": "~2.0.3", 433 | "isarray": "~1.0.0", 434 | "process-nextick-args": "~2.0.0", 435 | "safe-buffer": "~5.1.1", 436 | "string_decoder": "~1.1.1", 437 | "util-deprecate": "~1.0.1" 438 | } 439 | }, 440 | "node_modules/restore-cursor": { 441 | "version": "4.0.0", 442 | "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", 443 | "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", 444 | "dev": true, 445 | "dependencies": { 446 | "onetime": "^5.1.0", 447 | "signal-exit": "^3.0.2" 448 | }, 449 | "engines": { 450 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 451 | }, 452 | "funding": { 453 | "url": "https://github.com/sponsors/sindresorhus" 454 | } 455 | }, 456 | "node_modules/safe-buffer": { 457 | "version": "5.1.2", 458 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", 459 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", 460 | "dev": true 461 | }, 462 | "node_modules/semver": { 463 | "version": "7.6.2", 464 | "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", 465 | "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", 466 | "bin": { 467 | "semver": "bin/semver.js" 468 | }, 469 | "engines": { 470 | "node": ">=10" 471 | } 472 | }, 473 | "node_modules/setimmediate": { 474 | "version": "1.0.5", 475 | "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", 476 | "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", 477 | "dev": true 478 | }, 479 | "node_modules/signal-exit": { 480 | "version": "3.0.7", 481 | "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", 482 | "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", 483 | "dev": true 484 | }, 485 | "node_modules/stdin-discarder": { 486 | "version": "0.1.0", 487 | "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.1.0.tgz", 488 | "integrity": "sha512-xhV7w8S+bUwlPTb4bAOUQhv8/cSS5offJuX8GQGq32ONF0ZtDWKfkdomM3HMRA+LhX6um/FZ0COqlwsjD53LeQ==", 489 | "dev": true, 490 | "dependencies": { 491 | "bl": "^5.0.0" 492 | }, 493 | "engines": { 494 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 495 | }, 496 | "funding": { 497 | "url": "https://github.com/sponsors/sindresorhus" 498 | } 499 | }, 500 | "node_modules/string_decoder": { 501 | "version": "1.1.1", 502 | "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", 503 | "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", 504 | "dev": true, 505 | "dependencies": { 506 | "safe-buffer": "~5.1.0" 507 | } 508 | }, 509 | "node_modules/string-width": { 510 | "version": "6.1.0", 511 | "resolved": "https://registry.npmjs.org/string-width/-/string-width-6.1.0.tgz", 512 | "integrity": "sha512-k01swCJAgQmuADB0YIc+7TuatfNvTBVOoaUWJjTB9R4VJzR5vNWzf5t42ESVZFPS8xTySF7CAdV4t/aaIm3UnQ==", 513 | "dev": true, 514 | "dependencies": { 515 | "eastasianwidth": "^0.2.0", 516 | "emoji-regex": "^10.2.1", 517 | "strip-ansi": "^7.0.1" 518 | }, 519 | "engines": { 520 | "node": ">=16" 521 | }, 522 | "funding": { 523 | "url": "https://github.com/sponsors/sindresorhus" 524 | } 525 | }, 526 | "node_modules/strip-ansi": { 527 | "version": "7.1.0", 528 | "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", 529 | "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", 530 | "dev": true, 531 | "dependencies": { 532 | "ansi-regex": "^6.0.1" 533 | }, 534 | "engines": { 535 | "node": ">=12" 536 | }, 537 | "funding": { 538 | "url": "https://github.com/chalk/strip-ansi?sponsor=1" 539 | } 540 | }, 541 | "node_modules/util-deprecate": { 542 | "version": "1.0.2", 543 | "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", 544 | "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", 545 | "dev": true 546 | }, 547 | "node_modules/vscode-jsonrpc": { 548 | "version": "8.2.0", 549 | "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", 550 | "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", 551 | "engines": { 552 | "node": ">=14.0.0" 553 | } 554 | }, 555 | "node_modules/vscode-languageclient": { 556 | "version": "9.0.1", 557 | "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz", 558 | "integrity": "sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==", 559 | "dependencies": { 560 | "minimatch": "^5.1.0", 561 | "semver": "^7.3.7", 562 | "vscode-languageserver-protocol": "3.17.5" 563 | }, 564 | "engines": { 565 | "vscode": "^1.82.0" 566 | } 567 | }, 568 | "node_modules/vscode-languageserver-protocol": { 569 | "version": "3.17.5", 570 | "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", 571 | "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", 572 | "dependencies": { 573 | "vscode-jsonrpc": "8.2.0", 574 | "vscode-languageserver-types": "3.17.5" 575 | } 576 | }, 577 | "node_modules/vscode-languageserver-types": { 578 | "version": "3.17.5", 579 | "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", 580 | "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==" 581 | } 582 | } 583 | } 584 | -------------------------------------------------------------------------------- /vscode/client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "djlsp-client", 3 | "description": "Django Template Language Server Protocol client", 4 | "author": "Four Digits", 5 | "license": "MIT", 6 | "version": "0.0.1", 7 | "publisher": "fourdigits", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/fourdigits/django-template-lsp" 11 | }, 12 | "engines": { 13 | "vscode": "^1.75.0" 14 | }, 15 | "dependencies": { 16 | "vscode-languageclient": "^9.0.1" 17 | }, 18 | "devDependencies": { 19 | "@types/vscode": "^1.75.1", 20 | "@vscode/test-electron": "^2.3.9" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /vscode/client/src/extension.ts: -------------------------------------------------------------------------------- 1 | import * as os from 'os'; 2 | import * as fs from 'fs'; 3 | import { workspace, ExtensionContext } from 'vscode'; 4 | 5 | import { 6 | LanguageClient, 7 | LanguageClientOptions, 8 | StreamInfo, 9 | } from 'vscode-languageclient/node'; 10 | 11 | import { spawn } from 'child_process'; 12 | 13 | let client: LanguageClient; 14 | 15 | export function activate(context: ExtensionContext) { 16 | const expandHomeDir = (filePath: string) => { 17 | const home = os.homedir(); 18 | return home ? filePath.replace('~', home) : filePath; 19 | }; 20 | 21 | const configuration = workspace.getConfiguration('djangoTemplateLsp'); 22 | 23 | const djlspPaths = []; 24 | 25 | const djlspPathConfig = configuration.get('djlspPath', false); 26 | 27 | if (djlspPathConfig) { 28 | djlspPaths.push(expandHomeDir(djlspPathConfig)); 29 | } else { 30 | djlspPaths.push(expandHomeDir('~/.local/bin/djlsp')); 31 | djlspPaths.push(expandHomeDir('~/.local/pipx/venvs/django-template-lsp/bin/djlsp')); 32 | } 33 | 34 | const djlspPath = djlspPaths.find(fs.existsSync); 35 | 36 | // Add error handling for when djlsp is not installed 37 | if (!djlspPath) { 38 | throw new Error('djlsp is not installed'); 39 | } 40 | 41 | const djlspArgs = []; 42 | 43 | if (configuration.get("enableLogging", false)) { 44 | djlspArgs.push('--enable-log'); 45 | } 46 | 47 | // Pass initialization options to the server 48 | const initializationOptions = { 49 | docker_compose_file: configuration.get('dockerComposeFile', 'docker-compose.yml'), 50 | docker_compose_service: configuration.get('dockerComposeService', 'django'), 51 | django_settings_module: configuration.get('djangoSettingsModule', ''), 52 | }; 53 | 54 | // Get current workspace folder path 55 | // This is also updated when the workspace folder is changed. 56 | const workspaceFolders = workspace.workspaceFolders; 57 | if (workspaceFolders === undefined) { 58 | throw new Error('No workspace folder is open'); 59 | } 60 | const workspaceFolder = workspaceFolders[0]; 61 | const workspaceFolderPath = workspaceFolder.uri.path; 62 | 63 | const serverOptions = () => { 64 | const djlspProcess = spawn(djlspPath, djlspArgs, { 65 | stdio: ['pipe', 'pipe', 'pipe'], 66 | cwd: workspaceFolderPath, 67 | }); 68 | 69 | if (configuration.get("enableLogging", false)) { 70 | djlspProcess.stderr.on('data', (data) => { 71 | console.error(`djlsp stderr: ${data}`); 72 | }); 73 | 74 | djlspProcess.on('error', (err) => { 75 | console.error(`Failed to start djlsp: ${err.message}`); 76 | }); 77 | 78 | djlspProcess.on('exit', (code, signal) => { 79 | console.error(`djlsp exited with code ${code} and signal ${signal}`); 80 | }); 81 | 82 | djlspProcess.on('close', (code) => { 83 | console.error(`djlsp process closed with code ${code}`); 84 | }); 85 | 86 | djlspProcess.on('disconnect', () => { 87 | console.error('djlsp process disconnected'); 88 | }); 89 | } 90 | 91 | return Promise.resolve({ 92 | writer: djlspProcess.stdin, 93 | reader: djlspProcess.stdout, 94 | }); 95 | }; 96 | 97 | // Options to control the language client 98 | const clientOptions: LanguageClientOptions = { 99 | documentSelector: [ 100 | { scheme: 'file', language: 'html' }, 101 | { scheme: 'file', language: 'htmldjango' }, 102 | { scheme: 'file', language: 'django-html' }, 103 | ], // Adjust this to the appropriate language 104 | synchronize: { 105 | // Notify the server about file changes to '.clientrc files contained in the workspace 106 | fileEvents: workspace.createFileSystemWatcher('**/.clientrc'), 107 | }, 108 | initializationOptions: initializationOptions, 109 | }; 110 | 111 | // Create the language client and start the client. 112 | client = new LanguageClient( 113 | 'djlsp', 114 | 'Django Template Language Server', 115 | serverOptions, 116 | clientOptions, 117 | ); 118 | 119 | // Start the client. This will also launch the server 120 | client.start(); 121 | } 122 | 123 | export function deactivate(): Thenable | undefined { 124 | if (!client) { 125 | return undefined; 126 | } 127 | return client.stop(); 128 | } 129 | -------------------------------------------------------------------------------- /vscode/client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es2020", 5 | "lib": ["es2020"], 6 | "outDir": "out", 7 | "rootDir": "src", 8 | "sourceMap": true 9 | }, 10 | "include": ["src"], 11 | "exclude": ["node_modules", ".vscode-test"] 12 | } 13 | -------------------------------------------------------------------------------- /vscode/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fourdigits/django-template-lsp/7856324abd7583bbbae4577e449635ceb0594667/vscode/icon.png -------------------------------------------------------------------------------- /vscode/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "djlsp", 3 | "displayName": "Django Template LSP (djlsp)", 4 | "description": "The Django Template LSP server enhances your Django development experience with powerful features for navigating and editing template files.", 5 | "icon": "icon.png", 6 | "author": "Four Digits", 7 | "license": "GPL3", 8 | "version": "1.0.0", 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/fourdigits/django-template-lsp" 12 | }, 13 | "publisher": "FourDigits", 14 | "categories": ["Languages"], 15 | "keywords": [ 16 | "language", 17 | "client", 18 | "lsp", 19 | "django", 20 | "template" 21 | ], 22 | "engines": { 23 | "vscode": "^1.75.0" 24 | }, 25 | "activationEvents": [ 26 | "onLanguage:html", 27 | "onLanguage:django-html" 28 | ], 29 | "main": "./client/out/extension", 30 | "contributes": { 31 | "configuration": { 32 | "type": "object", 33 | "title": "Django Template LSP", 34 | "properties": { 35 | "djangoTemplateLsp.djlspPath": { 36 | "type": "string", 37 | "default": "", 38 | "description": "The path to the djlsp executable, by default it will search for djlsp in your .local directory" 39 | }, 40 | "djangoTemplateLsp.dockerComposeFile": { 41 | "type": "string", 42 | "default": "docker-compose.yml", 43 | "description": "The path to the docker-compose file" 44 | }, 45 | "djangoTemplateLsp.dockerComposeService": { 46 | "type": "string", 47 | "default": "django", 48 | "description": "The service name in the docker-compose file" 49 | }, 50 | "djangoTemplateLsp.djangoSettingsModule": { 51 | "type": "string", 52 | "default": "", 53 | "description": "The settings module to use" 54 | }, 55 | "djangoTemplateLsp.enableLogging": { 56 | "type": "boolean", 57 | "default": false, 58 | "description": "Enable logging" 59 | } 60 | } 61 | } 62 | }, 63 | "scripts": { 64 | "vscode:prepublish": "npm run compile", 65 | "compile": "tsc -b", 66 | "watch": "tsc -b -w", 67 | "lint": "eslint ./client/src --ext .ts,.tsx", 68 | "fix": "eslint ./client/src --ext .ts,.tsx --fix", 69 | "postinstall": "cd client && npm install && cd ..", 70 | "vsce-package": "vsce package --skip-license -o djlsp.vsix" 71 | }, 72 | "devDependencies": { 73 | "@types/mocha": "^10.0.6", 74 | "@types/node": "^18.14.6", 75 | "@typescript-eslint/eslint-plugin": "^7.1.0", 76 | "@typescript-eslint/parser": "^7.1.0", 77 | "eslint": "^8.57.0", 78 | "mocha": "^10.3.0", 79 | "typescript": "^5.3.3", 80 | "@vscode/vsce": "^2.25.0" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /vscode/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es2020", 5 | "lib": ["es2020"], 6 | "outDir": "out", 7 | "rootDir": "src", 8 | "sourceMap": true 9 | }, 10 | "include": [ 11 | "src" 12 | ], 13 | "exclude": [ 14 | "node_modules", 15 | ".vscode-test" 16 | ], 17 | "references": [ 18 | { "path": "./client" }, 19 | ] 20 | } 21 | --------------------------------------------------------------------------------