Compare commits

..

No commits in common. "primary" and "v0.2.1" have entirely different histories.

30 changed files with 3549 additions and 6195 deletions

View File

@ -6,16 +6,12 @@
# this notice are preserved. This file is offered as-is, without any warranty. # this notice are preserved. This file is offered as-is, without any warranty.
# #
# For history build logs, kind: pipeline
# see <https://ci.cismon.net/repos/cismonx/vscode-texinfo>. type: docker
name: default
steps: steps:
- name: build - name: build
image: node:18-alpine image: node:14.16
when:
- event: [push, tag, manual]
branch: primary
commands: commands:
- apk add --no-cache perl unzip - npm --unsafe-perm ci
- npm ci
- npm run package - npm run package

1
.gitignore vendored
View File

@ -6,7 +6,6 @@
# this notice are preserved. This file is offered as-is, without any warranty. # this notice are preserved. This file is offered as-is, without any warranty.
# #
*.asc
*.vsix *.vsix
.vscode/ .vscode/
node_modules/ node_modules/

View File

@ -8,7 +8,7 @@
**/*.map **/*.map
**/*.ts **/*.ts
.woodpecker.yml .drone.yml
.gitignore .gitignore
.gitattributes .gitattributes
.travis.yml .travis.yml

View File

@ -1,31 +1,13 @@
<!-- <!--
Copyright (C) 2020,2021,2022,2024 CismonX <admin@cismon.net> Copyright (C) 2020,2021 CismonX <admin@cismon.net>
Copying and distribution of this file, with or without modification, are Copying and distribution of this file, with or without modification, are
permitted in any medium without royalty, provided the copyright notice and permitted in any medium without royalty, provided the copyright notice and
this notice are preserved. This file is offered as-is, without any warranty. this notice are preserved. This file is offered as-is, without any warranty.
--> -->
# Changelog # Changelog
## v0.3.0 - 04/04/2024
* Add configuration for customization variables (`makeinfo -c KEY=VAL`).
* Support GNU Texinfo 7.1.
## v0.2.4 - 02/02/2022
* Fix a bug which breaks the snippet completion of block commands.
## v0.2.3 - 10/23/2021
* Fix a bug which prevents diagnostic info from displaying correctly in GNU Texinfo 6.8, and on Windows platform.
## v0.2.2 - 10/03/2021
* Fix a bug which breaks configuration `preview.includePaths` on Windows.
* Remove completion for commands which are deprecated in GNU Texinfo 6.8.
## v0.2.1 - 05/05/2021 ## v0.2.1 - 05/05/2021
* Fix an error in build script which produces corrupted metadata in `.vsix` package. * Fix an error in build script which produces corrupted metadata in `.vsix` package.

View File

@ -1,9 +1,9 @@
<!-- <!--
Copyright (C) 2021 CismonX <admin@cismon.net> Copyright (C) 2021 CismonX <admin@cismon.net>
Copying and distribution of this file, with or without modification, are Copying and distribution of this file, with or without modification, are
permitted in any medium without royalty, provided the copyright notice and permitted in any medium without royalty, provided the copyright notice and
this notice are preserved. This file is offered as-is, without any warranty. this notice are preserved. This file is offered as-is, without any warranty.
--> -->
# License Notice # License Notice
@ -13,32 +13,34 @@
Project files listed below cannot carry a license notice by themselves, due to Project files listed below cannot carry a license notice by themselves, due to
file format restrictions. file format restrictions.
assets/texinfo.png ```text
assets/texinfo.png
```
This file is released into the public domain using [CC0]. They should be treated as if they each contains the following text:
```text
Copyright (C) 2020,2021 CismonX <admin@cismon.net>
Copying and distribution of this file, with or without modification, are
permitted in any medium without royalty, provided the copyright notice and
this notice are preserved. This file is offered as-is, without any warranty.
```
## Files from other projects ## Files from other projects
Source code from the projects listed below are *not* part of vscode-texinfo. Source code from the projects listed below are **not** part of vscode-texinfo.
However, when building the project, they are downloaded, compiled, and packaged However, when building the project, they are downloaded, compiled, and packaged
into a single binary file alongside with vscode-texinfo. into a single binary file alongside with vscode-texinfo.
| Project | Copyright Holder | License | | Project | Copyright Holder | License |
| - | - | - | | - | - | - |
| [Texinfo syntax highlighting] | John Gardner | [ISC](https://github.com/Alhadis/language-texinfo/blob/master/LICENSE.md) | | [Texinfo syntax highlighting](https://github.com/Alhadis/language-texinfo) | John Gardner | [ISC](https://github.com/Alhadis/language-texinfo/blob/master/LICENSE.md) |
The following projects are required during runtime of vscode-texinfo, but as The following projects are required during runtime of vscode-texinfo, but as
separate programs. separate programs.
| Project | Copyright Holder | License | | Project | Copyright Holder | License |
| - | - | - | | - | - | - |
| [Visual Studio Code] | Microsoft Corporation | [MIT](https://github.com/microsoft/vscode/blob/main/LICENSE.txt) | | [Visual Studio Code](https://github.com/microsoft/vscode) | Microsoft Corporation | [MIT](https://github.com/microsoft/vscode/blob/main/LICENSE.txt) |
| [GNU Texinfo] | Free Software Foundation | [GPL-3.0](https://git.savannah.gnu.org/cgit/texinfo.git/tree/COPYING)-or-later | | [GNU Texinfo](https://www.gnu.org/software/texinfo) | Free Software Foundation | [GPL-3.0](https://git.savannah.gnu.org/cgit/texinfo.git/tree/COPYING)-or-later |
<!-- Reference Links -->
[CC0]: https://creativecommons.org/public-domain/cc0/
[Texinfo syntax highlighting]: https://github.com/Alhadis/language-texinfo
[Visual Studio Code]: https://github.com/microsoft/vscode
[GNU Texinfo]: https://www.gnu.org/software/texinfo

View File

@ -1,20 +1,21 @@
<!-- <!--
Copyright (C) 2020,2021,2024 CismonX <admin@cismon.net> Copyright (C) 2020,2021 CismonX <admin@cismon.net>
Copying and distribution of this file, with or without modification, are Copying and distribution of this file, with or without modification, are
permitted in any medium without royalty, provided the copyright notice and permitted in any medium without royalty, provided the copyright notice and
this notice are preserved. This file is offered as-is, without any warranty. this notice are preserved. This file is offered as-is, without any warranty.
--> -->
# vscode-texinfo # vscode-texinfo
[![License]](LICENSE) [![Build Status](https://shields.io/drone/build/CismonX/vscode-texinfo?server=https%3A%2F%2Fdrone.cismon.net)](https://drone.cismon.net/CismonX/vscode-texinfo)
[![License](https://img.shields.io/badge/license-GPL--3.0--or--later-blue.svg)](LICENSE)
## About ## About
vscode-texinfo is an extension of [Visual Studio Code] which provides the vscode-texinfo is an extension of Visual Studio Code which aims at improving user experience for editing Texinfo documents.
following features for editing [Texinfo] documents:
Major features include:
* Syntax Highlighting * Syntax Highlighting
* Code Completion * Code Completion
* HTML Preview * HTML Preview
@ -24,12 +25,4 @@ following features for editing [Texinfo] documents:
## Getting Started ## Getting Started
For instructions on how to install, use, and contribute to vscode-texinfo, For instructions about how to install, use, and contribute to vscode-texinfo, see the [online user manual](https://nongnu.org/vscode-texinfo/manual).
see the [user manual].
<!-- Reference Links -->
[Visual Studio Code]: https://github.com/microsoft/vscode
[Texinfo]: https://www.gnu.org/software/texinfo/
[License]: https://img.shields.io/badge/license-GPL--3.0--or--later-blue.svg
[user manual]: https://nongnu.org/vscode-texinfo/manual

View File

@ -9,8 +9,6 @@
@set vscode-docs-url https://code.visualstudio.com/docs @set vscode-docs-url https://code.visualstudio.com/docs
@set vscode-api-url https://code.visualstudio.com/api @set vscode-api-url https://code.visualstudio.com/api
@set gnu-texinfo-docs https://www.gnu.org/software/texinfo/manual/texinfo @set gnu-texinfo-docs https://www.gnu.org/software/texinfo/manual/texinfo
@set sv-home-url https://sv.nongnu.org
@set sv-releases-url https://dl.sv.nongnu.org/releases
@tex @tex
\global\def\linkcolor{0 0 1} \global\def\linkcolor{0 0 1}
@ -22,7 +20,7 @@
This manual is for vscode-texinfo (version @value{VERSION}), an extension of This manual is for vscode-texinfo (version @value{VERSION}), an extension of
Visual Studio Code. Visual Studio Code.
Copyright @copyright{} 2021,2024 CismonX <admin@@cismon.net> Copyright @copyright{} 2021 CismonX <admin@@cismon.net>
@quotation @quotation
This manual is licensed under a This manual is licensed under a
@ -53,7 +51,7 @@ Creative Commons Attribution-ShareAlike 4.0 International License}.
This manual is for vscode-texinfo (version @value{VERSION}), an extension of This manual is for vscode-texinfo (version @value{VERSION}), an extension of
Visual Studio Code. Visual Studio Code.
Copyright @copyright{} 2021,2024 CismonX <admin@@cismon.net> Copyright @copyright{} 2021 CismonX <admin@@cismon.net>
This manual is licensed under a This manual is licensed under a
@url{https://creativecommons.org/licenses/by-sa/4.0/, @url{https://creativecommons.org/licenses/by-sa/4.0/,
@ -74,8 +72,8 @@ Creative Commons Attribution-ShareAlike 4.0 International License}.
@chapter Overview @chapter Overview
Texinfo is a typesetting language designed for writing software manuals. It's Texinfo is a typesetting language designed for writing software manuals. It's
the official documentation format for GNU projects, but not as popular in the official documention format for GNU projects, but not as popular in modern
modern non-GNU free software projects. non-GNU free software projects.
One of the main reasons is the lack of editor support. While Emacs does offer a One of the main reasons is the lack of editor support. While Emacs does offer a
``texinfo-mode'', however, Emacs is not widely used among average software ``texinfo-mode'', however, Emacs is not widely used among average software
@ -83,10 +81,10 @@ developers.
We believe that Texinfo deserves more users, for it is an excellent format for We believe that Texinfo deserves more users, for it is an excellent format for
writing software manuals, as well as other technical materials. We chose Visual writing software manuals, as well as other technical materials. We chose Visual
Studio Code, one of the most popular code editors as of year 2020, and Studio Code, one of the most popular code editors as of year 2020, and developed
developed this very extension, vscode-texinfo, which provides some useful this very extension, vscode-texinfo, which provides some useful features for
features for Visual Studio Code regarding the Texinfo format, in the hope that Visual Studio Code regarding the Texinfo format, in the hope that more
more developers can benefit from it. developers can benefit from it.
vscode-texinfo is free software. You can redistribute it and/or modify it under vscode-texinfo is free software. You can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software the terms of the GNU General Public License as published by the Free Software
@ -101,11 +99,11 @@ version 3 of the License}, or (at your option) any later version.
@node Contributing @node Contributing
@section Contributing @section Contributing
This project is hosted on @url{@value{sv-home-url}/p/vscode-texinfo, Savannah}. This project is hosted on @url{https://sv.gnu.org/p/vscode-texinfo, Savannah}.
Any kind of contribution is welcome, including bug reports, patches, and Any kind of contribution is welcome, including bug reports, patches, and general
general discussions regarding the usage of vscode-texinfo. discussions regarding the usage of vscode-texinfo.
Before you post something, please make sure that you have read this manual, Before you submit something, please make sure that you have read this manual,
and no one else has posted the same content. and no one else has posted the same content.
@ -122,7 +120,7 @@ binary release, which is proprietary software. You can also build it from
@quotation Note @quotation Note
Theoretically vscode-texinfo can work with any version of Visual Studio Code Theoretically vscode-texinfo can work with any version of Visual Studio Code
since 1.82, but not all versions are tested. It's recommended to install a since 1.40, but not all versions are tested. It's recommended to install a
latest release. latest release.
@end quotation @end quotation
@ -141,21 +139,35 @@ and you can find and install this extension (Extension ID:
@section Manual Installation @section Manual Installation
You can manually download the @code{.vsix} file, from either Savannah's You can manually download the @code{.vsix} file, from either Savannah's
@url{@value{sv-releases-url}/vscode-texinfo/, download area}, @url{https://dl.sv.gnu.org/releases/vscode-texinfo/, download area},
@url{https://open-vsx.org/extension/CismonX/texinfo, Open VSX Registry}, or the @url{https://open-vsx.org/extension/CismonX/texinfo, Open VSX Registry}, or the
proprietary Visual Studio Marketplace. proprietary Visual Studio Marketplace.
Before you install a @code{.vsix} file downloaded from a third party, Before you install a @code{.vsix} file downloaded from a third party,
you should check whether the file matches a trusted signature: you should check whether the file matches a trusted signature:
@set vsix-name texinfo-@value{VERSION}.vsix @ifhtml
@example @example
wget -O- '@value{sv-home-url}/people/viewgpg.php?user_id=214244' \ wget -O cismonx.gpg.asc "https://sv.gnu.org/people/viewgpg.php?user_id=214244"
| gpg --import gpg --import cismonx.gpg.asc
wget -O- @value{sv-releases-url}/vscode-texinfo/@value{vsix-name}.sig.asc \
| gpg --verify - @value{vsix-name} wget https://dl.sv.gnu.org/releases/vscode-texinfo/texinfo-0.2.0.vsix.sig.asc
gpg --verify texinfo-0.2.0.vsix.sig.asc texinfo-0.2.0.vsix
@end example @end example
@end ifhtml
@ifnothtml
@example
wget -O cismonx.gpg.asc \
"https://sv.gnu.org/people/viewgpg.php?user_id=214244"
gpg --import cismonx.gpg.asc
wget "https://dl.sv.gnu.org/releases/vscode-texinfo/
texinfo-0.2.0.vsix.sig.asc"
gpg --verify texinfo-0.2.0.vsix.sig.asc texinfo-0.2.0.vsix
@end example
@end ifnothtml
Finally, install the @code{.vsix} file to Visual Studio Code via command Finally, install the @code{.vsix} file to Visual Studio Code via command
palette: @code{Extensions: Install from VSIX...}. palette: @code{Extensions: Install from VSIX...}.
@ -164,7 +176,7 @@ palette: @code{Extensions: Install from VSIX...}.
@node Build from Source @node Build from Source
@section Build from Source @section Build from Source
The @code{.vsix} file can be built from the source code of vscode-texinfo. You can generate the @code{.vsix} file from the source code of vscode-texinfo.
First, clone the source code repository: First, clone the source code repository:
@ -211,8 +223,8 @@ suffix @code{.texi}, @code{.txi} or @code{.texinfo}, this process should be
automatic. If not, find and click the status bar item with ``Select Language automatic. If not, find and click the status bar item with ``Select Language
Mode'' tooltip, then choose ``Texinfo'' in the menu which just popped up. Mode'' tooltip, then choose ``Texinfo'' in the menu which just popped up.
If syntax highlighting does not look satisfactory, try another color theme If syntax highlighting does not look satisfactory, try another color theme where
where keyword/operator colors are distinct. Some good examples are Solarized keyword/operator colors are distinct. Some good examples are Solarized
Light/Dark, Monokai, etc. Light/Dark, Monokai, etc.
For details about how to @url{@value{vscode-docs-url} For details about how to @url{@value{vscode-docs-url}
@ -253,10 +265,10 @@ code snippets is disabled by default. You can re-enable it on by switching off
@quotation Note @quotation Note
Code completion provided by vscode-texinfo does not recognize much of Texinfo's Code completion provided by vscode-texinfo does not recognize much of Texinfo's
semantics, and completion may appear in contexts where it should not exist. semantics, and completion may appear in contexts where it should not exist. This
This is a known bug (which cannot be fixed in near future, unless a is a known bug (which cannot be fixed in near future, unless a
@url{https://microsoft.github.io/language-server-protocol/, language server} @url{https://microsoft.github.io/language-server-protocol/, language server} for
for Texinfo is implemented, which is not trivial). Texinfo is implemented, which is not trivial).
@end quotation @end quotation
@ -274,15 +286,14 @@ Three types of code blocks can be recognized by vscode-texinfo:
@item Consecutive lines of comments @item Consecutive lines of comments
@end itemize @end itemize
While editing a Texinfo document, you can collapse or expand a code block While editing a Texinfo document, you can collapse or expand a code block either
either by clicking the folding icon to the left of the first line of the block, by clicking the folding icon to the left of the first line of the block, or by
or by invoking a corresponding command. See the Visual Studio Code User Guide invoking a corresponding command. See the Visual Studio Code User Guide for
for @url{@value{vscode-docs-url}/editor/codebasics#_folding, details}. @url{@value{vscode-docs-url}/editor/codebasics#_folding, details}.
@quotation Note @quotation Note
Due to performance issues, the block hierarchy of a Texinfo document is Due to performance issues, the block hierarchy of a Texinfo document is
re-calculated only when total line count changes, or when the document is re-calculated only when total line count changes, or when the document is saved.
saved.
@end quotation @end quotation
@ -303,10 +314,10 @@ See the Visual Studio Code User Guide for more information about
Some more advanced features of vscode-texinfo is available if GNU Texinfo is Some more advanced features of vscode-texinfo is available if GNU Texinfo is
correctly installed and configured on your device. correctly installed and configured on your device.
@url{https://www.gnu.org/software/texinfo, GNU Texinfo} is the official (and @url{https://www.gnu.org/software/texinfo, GNU Texinfo} is the official (and the
the only known) full implementation of Texinfo. On most platforms, it can be only known) full implementation of Texinfo. On most platforms, it can be easily
easily installed using a package manager. For example, if you're using a installed using a package manager. For example, if you're using a Debian-based
Debian-based GNU/Linux distribution, you can install GNU Texinfo with: GNU/Linux distribution, you can install GNU Texinfo with:
@example @example
sudo apt-get install texinfo sudo apt-get install texinfo
@ -318,8 +329,8 @@ plain text, etc.
To specify the location of @code{makeinfo}, edit the configuration item To specify the location of @code{makeinfo}, edit the configuration item
@code{texinfo.makeinfo}. If it's not located in @code{$PATH}, an absolute path @code{texinfo.makeinfo}. If it's not located in @code{$PATH}, an absolute path
should be specified. Also note that the path should not contain any command should be specified. Also note that the path should not contain any command line
line arguments. arguments.
To check whether GNU Texinfo is correctly installed and configured, see To check whether GNU Texinfo is correctly installed and configured, see
@ref{Version Indicator}. @ref{Version Indicator}.
@ -335,20 +346,20 @@ To check whether GNU Texinfo is correctly installed and configured, see
@section Version Indicator @section Version Indicator
The version indicator is a status bar item with text ``GNU Texinfo''. It is The version indicator is a status bar item with text ``GNU Texinfo''. It is
located on the right side of the status bar, which is shown when the active located on the right side of the status bar, which is shown when the active text
text editor contains a Texinfo document. editor contains a Texinfo document.
If you see a @b{check icon} and the version of GNU Texinfo, then If you see a @b{check icon} and the version of GNU Texinfo, then
congratulations, you're all set. If a @b{cross icon} is displayed, it means congratulations, you're all set. If a @b{cross icon} is displayed, it means
that GNU Texinfo is @emph{not} correctly installed and configured. that GNU Texinfo is @emph{not} correctly installed and configured.
If a @b{warning icon} is displayed, it means that the currently installed GNU If a @b{warning icon} is displayed, it means that the currently installed GNU
Texinfo is outdated, or has an unrecognizable version number. In that case, Texinfo is outdated, or has an unrecognizable version number. In that case, some
some features may not work as expected. features may not work as expected.
@quotation Note @quotation Note
The version indicator does not automatically refresh since the activation of The version indicator does not automatically refresh since the activation of the
the extension. To manually trigger a refresh, click the status bar item. extension. To manually trigger a refresh, click the status bar item.
@end quotation @end quotation
@ -356,13 +367,13 @@ the extension. To manually trigger a refresh, click the status bar item.
@section HTML Preview @section HTML Preview
You can generate the HTML preview of a Texinfo document in Visual Studio Code, You can generate the HTML preview of a Texinfo document in Visual Studio Code,
to see how the document looks like when displayed in a web browser. to see how the document looks like when displayed online.
In the active text editor which contains a Texinfo document, click the ``Show In the active text editor which contains a Texinfo document, click the ``Show
Preview'' button on the top right of the editor. A webview will be created in a Preview'' button on the top right of the editor. A webview will be created in a
split editor (if not already), and the HTML preview will be displayed there. split editor (if not already), and the HTML preview will be displayed there. The
The ``Show Preview'' command is also available in command palette, and has a ``Show Preview'' command is also available in command palette, and has a default
default @code{Ctrl+K V} key binding (on GNU/Linux). @code{Ctrl+K V} key binding (on GNU/Linux).
The HTML used for preview is generated by @code{makeinfo --html --nosplit}, and The HTML used for preview is generated by @code{makeinfo --html --nosplit}, and
Texinfo source is read from disk, instead of taken from a Texinfo source is read from disk, instead of taken from a
@ -391,12 +402,11 @@ means that the preview is being updated.
You can use a custom CSS to make the HTML preview look prettier. To configure You can use a custom CSS to make the HTML preview look prettier. To configure
this, edit the configuration option @code{texinfo.preview.customCSS}. The CSS this, edit the configuration option @code{texinfo.preview.customCSS}. The CSS
file can either be an online or a local (starting with @code{file://}) file can either be an online or a local (starting with @code{file://}) resource.
resource.
A good example is @url{https://www.gnu.org/software/gnulib/manual.css}, which A good example is @url{https://www.gnu.org/software/gnulib/manual.css}, which is
is popular among manuals of GNU projects. (Note: May require some tinkering popular among manuals of GNU projects. (Note: May require some tinkering when
when used with darker editor themes) used with darker editor themes)
@node Goto Node @node Goto Node
@ -413,7 +423,7 @@ allow @@-commands}, which is not handled in vscode-texinfo due to performance
considerations. For these nodes, this feature does not work. considerations. For these nodes, this feature does not work.
@end quotation @end quotation
To disable this feature and hide the code lenses, switch off the configuration To disable this feature and hide the code lenses, switch off the configuation
item @code{texinfo.enableCodeLens}. item @code{texinfo.enableCodeLens}.
See the Visual Studio Code User Guide for more information about See the Visual Studio Code User Guide for more information about
@ -431,7 +441,7 @@ HTML previews.
can produce before quitting. (@code{--error-limit=NUM}) can produce before quitting. (@code{--error-limit=NUM})
@item @code{texinfo.preview.includePaths}: Array of extra paths to search for @item @code{texinfo.preview.includePaths}: Array of extra paths to search for
@code{@@include} files. (@code{-I PATH}) @code{@@include} files. (@code{-I PATH})
@item @code{texinfo.preview.maxSize}: Max allowed size for the generated HTML @item @code{texinfo.preview.maxSize}: Max allowed size for the genereated HTML
file before it's displayed in the preview. Files larger than this limit will file before it's displayed in the preview. Files larger than this limit will
trigger an error. trigger an error.
@item @code{texinfo.preview.noHeaders}: When enabled, headers and menus are no @item @code{texinfo.preview.noHeaders}: When enabled, headers and menus are no
@ -443,8 +453,6 @@ are not validated. (@code{--no-validate})
@item @code{texinfo.preview.variables}: Array of variables to define (as with @item @code{texinfo.preview.variables}: Array of variables to define (as with
@code{@@set}). If a variable has a value, use the ASCII space character to @code{@@set}). If a variable has a value, use the ASCII space character to
separate key and value. separate key and value.
@item @code{texinfo.preview.customizationVariables}: Array of customization
variables. (@code{-c KEY=VALUE})
@end itemize @end itemize

6851
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"_copyrightNotice": [ "_copyrightNotice": [
"Copyright (C) 2020,2021,2022,2024 CismonX <admin@cismon.net>", "Copyright (C) 2020,2021 CismonX <admin@cismon.net>",
"Copying and distribution of this file, with or without modification,", "Copying and distribution of this file, with or without modification,",
"are permitted in any medium without royalty, provided the copyright notice and this notice are preserved.", "are permitted in any medium without royalty, provided the copyright notice and this notice are preserved.",
"This file is offered as-is, without any warranty." "This file is offered as-is, without any warranty."
@ -9,37 +9,38 @@
"displayName": "Texinfo Language Support", "displayName": "Texinfo Language Support",
"description": "Texinfo language support for Visual Studio Code", "description": "Texinfo language support for Visual Studio Code",
"publisher": "cismonx", "publisher": "cismonx",
"version": "0.3.0", "version": "0.2.1",
"author": { "author": {
"name": "CismonX", "name": "CismonX",
"email": "admin@cismon.net", "email": "admin@cismon.net",
"url": "https://cismon.net" "url": "https://cismon.net"
}, },
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"homepage": "https://savannah.nongnu.org/p/vscode-texinfo", "homepage": "https://sv.gnu.org/p/vscode-texinfo",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.savannah.nongnu.org/cgit/vscode-texinfo.git" "url": "https://git.sv.gnu.org/cgit/vscode-texinfo.git"
}, },
"icon": "assets/texinfo.png", "icon": "assets/texinfo.png",
"devDependencies": { "devDependencies": {
"@types/node": "^18.11.9", "@types/node": "^14.14.43",
"@types/vscode": "~1.82.0", "@types/terser-webpack-plugin": "^5.0.3",
"@types/webpack": "^5.28.5", "@types/vscode": "~1.40.0",
"@typescript-eslint/eslint-plugin": "^7.5.0", "@types/webpack": "^5.28.0",
"@typescript-eslint/parser": "^7.5.0", "@typescript-eslint/eslint-plugin": "^4.22.1",
"@vscode/vsce": "^2.24.0", "@typescript-eslint/parser": "^4.22.1",
"cson": "^8.4.0", "cson": "^7.20.0",
"eslint": "^8.57.0", "eslint": "^7.25.0",
"json": "^11.0.0", "json": "^11.0.0",
"json5": "^2.2.3", "json5": "^2.2.0",
"language-texinfo": "^1.1.0", "language-texinfo": "^1.0.0",
"minify-xml": "^4.4.1", "minify-xml": "^2.5.0",
"ts-loader": "^9.5.1", "ts-loader": "^9.1.1",
"ts-node": "^10.9.2", "ts-node": "^9.1.1",
"typescript": "^5.4.3", "typescript": "^4.2.4",
"webpack": "^5.91.0", "vsce": "^1.87.0",
"webpack-cli": "^5.1.4" "webpack": "^5.35.1",
"webpack-cli": "^4.6.0"
}, },
"scripts": { "scripts": {
"vscode:prepublish": "webpack --mode production", "vscode:prepublish": "webpack --mode production",
@ -71,7 +72,7 @@
"max-len": [ "max-len": [
"warn", "warn",
{ {
"code": 79 "code": 120
} }
], ],
"@typescript-eslint/explicit-module-boundary-types": "off", "@typescript-eslint/explicit-module-boundary-types": "off",
@ -79,7 +80,7 @@
} }
}, },
"engines": { "engines": {
"vscode": "^1.82.0" "vscode": "^1.40.0"
}, },
"categories": [ "categories": [
"Programming Languages", "Programming Languages",
@ -87,6 +88,9 @@
"Other" "Other"
], ],
"main": "./out/extension.js", "main": "./out/extension.js",
"activationEvents": [
"onLanguage:texinfo"
],
"contributes": { "contributes": {
"commands": [ "commands": [
{ {
@ -163,7 +167,7 @@
"texinfo.makeinfo": { "texinfo.makeinfo": {
"type": "string", "type": "string",
"default": "makeinfo", "default": "makeinfo",
"description": "Path to the makeinfo (or texi2any) program." "description": "Path to the makeinfo (or texi2any) command."
}, },
"texinfo.preview.customCSS": { "texinfo.preview.customCSS": {
"type": "string", "type": "string",
@ -201,17 +205,12 @@
"texinfo.preview.noValidation": { "texinfo.preview.noValidation": {
"type": "boolean", "type": "boolean",
"default": false, "default": false,
"description": "Suppress node cross-reference validation." "description": "Supress node cross-reference validation."
}, },
"texinfo.preview.variables": { "texinfo.preview.variables": {
"type": "array", "type": "array",
"default": [], "default": [],
"description": "Define variables (as with @set)." "description": "Define variables (as with @set)."
},
"texinfo.preview.customizationVariables": {
"type": "array",
"default": [],
"description": "Set customization variables (format: KEY=VAL)"
} }
} }
}, },

View File

@ -1,45 +1,38 @@
#!/bin/sh #!/usr/bin/env bash
# #
# Copyright (C) 2021,2024 CismonX <admin@cismon.net> # Copyright (C) 2021 CismonX <admin@cismon.net>
# #
# Copying and distribution of this file, with or without modification, are # Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty, provided the copyright notice and # permitted in any medium without royalty, provided the copyright notice and
# this notice are preserved. This file is offered as-is, without any warranty. # this notice are preserved. This file is offered as-is, without any warranty.
# #
set -e VSIX_FILE_NAME=texinfo-$(json -f package.json version).vsix
PACKAGE_JSON_CLEANUP_JS=$(cat ./scripts/package-json-cleanup.js)
version=$(json -f package.json version) vsce package --baseContentUrl=$(json -f package.json repository.url)/tree
vsix_file_name=texinfo-$version.vsix
vsce package --baseContentUrl="$(json -f package.json repository.url)/tree"
unzip -d "$vsix_file_name.d" "$vsix_file_name"
cd "$vsix_file_name.d"
minify_xml() {
minify-xml --no-shorten-namespaces --no-remove-unused-namespaces \
--no-remove-unused-default-namespace -i "$1"
}
minify_xml '[Content_Types].xml'
minify_xml extension.vsixmanifest
unzip -d $VSIX_FILE_NAME{.d,}
cd $VSIX_FILE_NAME.d
MINIFY_XML_OPTIONS='--no-shorten-namespaces --no-remove-unused-namespaces --no-remove-unused-default-namespace'
minify-xml $MINIFY_XML_OPTIONS --output \[Content_Types\].xml{,}
minify-xml $MINIFY_XML_OPTIONS --output extension.vsixmanifest{,}
cd extension cd extension
# Minify JSON files. # Minify JSON files.
json -j0 -I -e "$(cat ../../scripts/package-json-cleanup.js)" -f package.json json -j0 -I -e "$PACKAGE_JSON_CLEANUP_JS" -f package.json
perl -pi -e 'chomp if eof' package.json perl -pi -e 'chomp if eof' package.json
json5 language-configuration.json > _ && mv _ language-configuration.json json5 -o language-configuration.json{,}
# Remove comments from Markdown files. # Remove comments from Markdown files.
tail -n +9 README.md > _ && mv _ README.md tail -n +9 README.md > _ && mv _ README.md
tail -n +9 CHANGELOG.md > _ && mv _ CHANGELOG.md tail -n +9 CHANGELOG.md > _ && mv _ CHANGELOG.md
cd ext cd ext
# Minify Perl scripts. # Minify Perl scripts.
# You can install perltidy with `cpan Perl::Tidy` if [ -x "$(command -v perltidy)" ]; then
if command -v perltidy; then
perltidy --mangle -dac -b html-preview.pm perltidy --mangle -dac -b html-preview.pm
rm html-preview.pm.bak rm html-preview.pm.bak
fi fi
cd ../../.. cd ../../..
# Re-package .vsix file. # Re-package .vsix file.
node ./scripts/make-vsix.js "$vsix_file_name" node ./scripts/make-vsix.js $VSIX_FILE_NAME
rm -r "$vsix_file_name.d" rm -r $VSIX_FILE_NAME.d

View File

@ -1,21 +1,17 @@
#!/bin/sh #!/usr/bin/env sh
# #
# Copyright (C) 2020,2021,2024 CismonX <admin@cismon.net> # Copyright (C) 2020,2021 CismonX <admin@cismon.net>
# #
# Copying and distribution of this file, with or without modification, are # Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty, provided the copyright notice and # permitted in any medium without royalty, provided the copyright notice and
# this notice are preserved. This file is offered as-is, without any warranty. # this notice are preserved. This file is offered as-is, without any warranty.
# #
set -e SRC_PATH=./node_modules/language-texinfo
DEST_PATH=./out/grammars
mkdir -p $DEST_PATH
# Convert TextMate grammar from CSON to JSON, as VSCode cannot recognize CSON ones.
cson2json $SRC_PATH/grammars/texinfo.cson | json5 > $DEST_PATH/texinfo.json
src_path=./node_modules/language-texinfo VERSION=$(json -f package.json version)
dest_path=./out/grammars echo "@set VERSION $VERSION" > ./doc/version.texi
mkdir -p $dest_path
# Convert TextMate grammar to JSON, since VSCode cannot recognize CSON ones.
cson2json $src_path/grammars/texinfo.cson | json5 > $dest_path/texinfo.json
version=$(json -f package.json version)
echo "@set VERSION $version" > ./doc/version.texi

View File

@ -25,11 +25,10 @@ import GlobalContext from './global_context';
import { prompt } from './utils/misc'; import { prompt } from './utils/misc';
/** /**
* Manage mappings between Texinfo documents and corresponding * Manage mappings between Texinfo documents and corresponding document-specific contexts.
* document-specific contexts.
*/ */
export default class ContextMapping implements vscode.Disposable export default class ContextMapping implements vscode.Disposable {
{
/** /**
* Get context of a Texinfo document. Create one if not exists. * Get context of a Texinfo document. Create one if not exists.
* *
@ -37,47 +36,32 @@ export default class ContextMapping implements vscode.Disposable
* @returns * @returns
*/ */
getDocumentContext(document: vscode.TextDocument) { getDocumentContext(document: vscode.TextDocument) {
let documentContext = this._map.get(document); let documentContext = this.map.get(document);
if (documentContext === undefined) { if (documentContext === undefined) {
documentContext documentContext = new DocumentContext(this.globalContext, document);
= new DocumentContext(this._globalContext, document); this.map.set(document, documentContext);
this._map.set(document, documentContext);
} }
return documentContext; return documentContext;
} }
dispose() { dispose() {
this._map this.map.forEach(documentContext => documentContext.getPreview()?.close());
.forEach(documentContext => documentContext.getPreview()?.close());
} }
constructor(private readonly _globalContext: GlobalContext) { constructor(private readonly globalContext: GlobalContext) {
_globalContext.subscribe( globalContext.subscribe(
vscode.commands.registerTextEditorCommand( vscode.commands.registerTextEditorCommand('texinfo.preview.show', this.showPreview.bind(this)),
'texinfo.preview.show', vscode.commands.registerCommand('texinfo.preview.goto', this.gotoPreview.bind(this)),
this._showPreview.bind(this), vscode.workspace.onDidChangeTextDocument(this.onDocumentUpdate.bind(this)),
), vscode.workspace.onDidCloseTextDocument(this.onDocumentClose.bind(this)),
vscode.commands.registerCommand( vscode.workspace.onDidSaveTextDocument(this.onDocumentSave.bind(this)),
'texinfo.preview.goto',
this._gotoPreview.bind(this),
),
vscode.workspace.onDidChangeTextDocument(
this._onDocumentUpdate.bind(this),
),
vscode.workspace.onDidCloseTextDocument(
this._onDocumentClose.bind(this),
),
vscode.workspace.onDidSaveTextDocument(
this._onDocumentSave.bind(this),
),
); );
} }
private readonly _map = new Map<vscode.TextDocument, DocumentContext>(); private readonly map = new Map<vscode.TextDocument, DocumentContext>();
private _tryGetDocumentContext(document: vscode.TextDocument) { private tryGetDocumentContext(document: vscode.TextDocument) {
return document.languageId === 'texinfo' return document.languageId === 'texinfo' ? this.getDocumentContext(document) : undefined;
? this.getDocumentContext(document) : undefined;
} }
/** /**
@ -86,26 +70,24 @@ export default class ContextMapping implements vscode.Disposable
* @param document * @param document
* @param nodeName * @param nodeName
*/ */
private _gotoPreview(document: vscode.TextDocument, nodeName: string) { private gotoPreview(document: vscode.TextDocument, nodeName: string) {
this.getDocumentContext(document).initPreview().goto(nodeName); this.getDocumentContext(document).initPreview().goto(nodeName);
} }
private _onDocumentClose(document: vscode.TextDocument) { private onDocumentClose(document: vscode.TextDocument) {
this._map.get(document)?.getPreview()?.close(); this.map.get(document)?.getPreview()?.close();
this._map.delete(document); this.map.delete(document);
} }
private _onDocumentSave(document: vscode.TextDocument) { private onDocumentSave(document: vscode.TextDocument) {
const documentContext = this._tryGetDocumentContext(document); const documentContext = this.tryGetDocumentContext(document);
if (documentContext === undefined) { if (documentContext === undefined) return;
return;
}
documentContext.foldingRange.clear(); documentContext.foldingRange.clear();
documentContext.getPreview()?.updateWebview(); documentContext.getPreview()?.updateWebview();
} }
private _onDocumentUpdate(event: vscode.TextDocumentChangeEvent) { private onDocumentUpdate(event: vscode.TextDocumentChangeEvent) {
const documentContext = this._tryGetDocumentContext(event.document); const documentContext = this.tryGetDocumentContext(event.document);
if (documentContext?.foldingRange.update(event.contentChanges)) { if (documentContext?.foldingRange.update(event.contentChanges)) {
documentContext.documentSymbol.clear(); documentContext.documentSymbol.clear();
} }
@ -116,14 +98,11 @@ export default class ContextMapping implements vscode.Disposable
* *
* @param editor The editor where the document is being held. * @param editor The editor where the document is being held.
*/ */
private async _showPreview(editor: vscode.TextEditor) { private async showPreview(editor: vscode.TextEditor) {
const document = editor.document; const document = editor.document;
// Only show preview for saved files, as we're not gonna send // Only show preview for saved files, as we're not gonna send document content to `makeinfo` via STDIN.
// document content to `makeinfo` via STDIN.
// Instead, the file will be loaded from disk. // Instead, the file will be loaded from disk.
if (document.isUntitled && if (document.isUntitled && !await prompt('Save this document to display preview.', 'Save')) {
!await prompt('Save this document to display preview.', 'Save')
) {
return; return;
} }
if (document.isDirty && !await document.save()) { if (document.isDirty && !await document.save()) {

View File

@ -28,28 +28,25 @@ import PreviewContext from './preview';
/** /**
* Holds all contexts for a Texinfo document. * Holds all contexts for a Texinfo document.
*/ */
export default class DocumentContext export default class DocumentContext {
{
readonly foldingRange = new FoldingRangeContext(this); readonly foldingRange = new FoldingRangeContext(this);
readonly documentSymbol = new DocumentSymbolContext(this); readonly documentSymbol = new DocumentSymbolContext(this);
initPreview() { initPreview() {
return this._preview ??= new PreviewContext(this); return this.preview ??= new PreviewContext(this);
} }
getPreview() { getPreview() {
return this._preview; return this.preview;
} }
closePreview() { closePreview() {
this._preview = undefined; this.preview = undefined;
} }
constructor( constructor(readonly globalContext: GlobalContext, readonly document: vscode.TextDocument) {}
readonly globalContext: GlobalContext,
readonly document: vscode.TextDocument,
) {}
private _preview?: PreviewContext; private preview?: PreviewContext;
} }

View File

@ -27,52 +27,43 @@ import { FoldingRange, Optional } from '../utils/types';
/** /**
* Context for symbols in a Texinfo document. * Context for symbols in a Texinfo document.
*/ */
export default class DocumentSymbolContext export default class DocumentSymbolContext {
{
get documentSymbols() { get documentSymbols() {
return this._documentSymbols ??= this._calculateDocumentSymbols(); return this._documentSymbols ??= this.calculcateDocumentSymbols();
} }
clear() { clear() {
this._documentSymbols = undefined; this._documentSymbols = undefined;
} }
constructor(private readonly _documentContext: DocumentContext) {} constructor(private readonly documentContext: DocumentContext) {}
private _documentSymbols?: vscode.DocumentSymbol[]; private _documentSymbols?: vscode.DocumentSymbol[];
private readonly _document = this._documentContext.document; private readonly document = this.documentContext.document;
/** /**
* Calculate document symbols based on folding ranges. * Calculate document symbols based on folding ranges.
*/ */
private _calculateDocumentSymbols() { private calculcateDocumentSymbols() {
const ranges = Array<Optional<FoldingRange>>(this._document.lineCount); const ranges = Array<Optional<FoldingRange>>(this.document.lineCount);
this._documentContext.foldingRange.foldingRanges this.documentContext.foldingRange.foldingRanges
.filter(range => range.kind === undefined) .filter(range => range.kind === undefined)
.forEach(range => ranges[range.start] = range); .forEach(range => ranges[range.start] = range);
return foldingRangeToSymbols(ranges, 0, ranges.length); return foldingRangeToSymbols(ranges, 0, ranges.length);
} }
} }
function foldingRangeToSymbols( function foldingRangeToSymbols(ranges: readonly Optional<FoldingRange>[], start: number, end: number) {
ranges: readonly Optional<FoldingRange>[],
start: number,
end: number,
) {
const symbols = <vscode.DocumentSymbol[]>[]; const symbols = <vscode.DocumentSymbol[]>[];
for (let idx = start; idx < end; ++idx) { for (let idx = start; idx < end; ++idx) {
const node = ranges[idx]; const node = ranges[idx];
if (node === undefined) { if (node === undefined) continue;
continue; const range = lineNumToRange(idx, node.end);
} const selectionRange = lineNumToRange(idx);
const symbol = new vscode.DocumentSymbol( const symbol = new vscode.DocumentSymbol('@' + node.name, node.detail, vscode.SymbolKind.String,
'@' + node.name, range, selectionRange);
node.detail,
vscode.SymbolKind.String,
lineNumToRange(idx, node.end), // full range
lineNumToRange(idx), // selection range
);
symbol.children = foldingRangeToSymbols(ranges, idx + 1, node.end); symbol.children = foldingRangeToSymbols(ranges, idx + 1, node.end);
symbols.push(symbol); symbols.push(symbol);
idx = node.end; idx = node.end;

View File

@ -27,24 +27,24 @@ import DocumentContext from './document';
/** /**
* Stores information about folding ranges for a document. * Stores information about folding ranges for a document.
* *
* Actually, more than folding ranges (e.g. code lens) is handled within * Actually, more than folding ranges (e.g. code lens) is handled within this context, so I believe
* this context, so perhaps we should use another name... * we should use another name...
*/ */
export default class FoldingRangeContext export default class FoldingRangeContext {
{
/** /**
* Get VSCode folding ranges from the context. * Get VSCode folding ranges from the context.
*/ */
get foldingRanges() { get foldingRanges() {
return this._foldingRanges ?? this._calculateFoldingRanges(); return this._foldingRanges ?? this.calculateFoldingRanges();
} }
/** /**
* Get node values of document as VSCode code lenses. * Get node values of document as VSCode code lenses.
*/ */
get nodeValues() { get nodeValues() {
this._foldingRanges ?? this._calculateFoldingRanges(); this._foldingRanges ?? this.calculateFoldingRanges();
return this._nodes; return this.nodes;
} }
/** /**
@ -53,18 +53,14 @@ export default class FoldingRangeContext
* @param events Events describing the changes in the document. * @param events Events describing the changes in the document.
*/ */
update(events: readonly vscode.TextDocumentContentChangeEvent[]) { update(events: readonly vscode.TextDocumentContentChangeEvent[]) {
this._contentMayChange = true; this.contentMayChange = true;
if (this._foldingRanges === undefined) { if (this._foldingRanges === undefined) return false;
return false; const eol = this.document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
}
const eol = this._document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
for (const event of events) { for (const event of events) {
// Clear cached folding range when line count changes. // Clear cached folding range when line count changes.
if (event.text.split(eol).length !== 1 || if (event.text.split(eol).length !== 1 || event.range.start.line !== event.range.end.line) {
event.range.start.line !== event.range.end.line
) {
this._foldingRanges = undefined; this._foldingRanges = undefined;
this._nodes = []; this.nodes = [];
return true; return true;
} }
} }
@ -72,48 +68,40 @@ export default class FoldingRangeContext
} }
clear() { clear() {
if (this._contentMayChange) { if (this.contentMayChange) {
this._foldingRanges = undefined; this._foldingRanges = undefined;
} }
} }
constructor(private readonly _documentContext: DocumentContext) {} constructor(private readonly documentContext: DocumentContext) {}
private readonly _document = this._documentContext.document; private readonly document = this.documentContext.document;
/** /**
* Regex for matching subsection/section/chapter (-like) commands. * Regex for matching subsection/section/chapter (-like) commands.
*/ */
private static readonly _nodeFormat = RegExp('^@(?:(node)|' + private static readonly nodeFormat = RegExp('^@(?:(node)|(subsection|unnumberedsubsec|appendixsubsec|subheading)|' +
'(subsection|unnumberedsubsec|appendixsubsec|subheading)|' + '(section|unnumberedsec|appendixsec|heading)|(chapter|unnumbered|appendix|majorheading|chapheading)) (.*)$');
'(section|unnumberedsec|appendixsec|heading)|' +
'(chapter|unnumbered|appendix|majorheading|chapheading)) (.*)$');
private _foldingRanges?: FoldingRange[]; private _foldingRanges?: FoldingRange[];
private _nodes = <vscode.CodeLens[]>[]; private nodes = <vscode.CodeLens[]>[];
private _commentRange?: Range; private commentRange?: Range;
private _headerStart?: number; private headerStart?: number;
private _closingChapter?: number; private closingChapter?: number;
private _closingSection?: number; private closingSection?: number;
private _closingSubsection?: number; private closingSubsection?: number;
private _contentMayChange = true; private contentMayChange = true;
private _addRange(start: number, end: number, extraArgs: { private addRange(start: number, end: number, extraArgs: {
name?: string, name?: string,
detail?: string, detail?: string,
kind?: vscode.FoldingRangeKind kind?: vscode.FoldingRangeKind
}) { }) {
const items = { (this._foldingRanges ??= [])
name: extraArgs.name ?? '', .push({ name: extraArgs.name ?? '', detail: extraArgs.detail ?? '', start, end, kind: extraArgs.kind });
detail: extraArgs.detail ?? '',
start,
end,
kind: extraArgs.kind,
};
(this._foldingRanges ??= []).push(items);
} }
/** /**
@ -122,36 +110,30 @@ export default class FoldingRangeContext
* @param start Starting line number. * @param start Starting line number.
* @param end Ending line number. * @param end Ending line number.
*/ */
private _calculateFoldingRanges() { private calculateFoldingRanges() {
this._contentMayChange = false; this.contentMayChange = false;
this._foldingRanges = []; this._foldingRanges = [];
this._clearTemporaries(); this.clearTemporaries();
let closingBlocks = <NamedLine[]>[]; let closingBlocks = <NamedLine[]>[];
let lastLine = this._document.lineCount - 1; let lastLine = this.document.lineCount - 1;
let verbatim = false; let verbatim = false;
for (let idx = lastLine; idx >= 0; --idx) { for (let idx = lastLine; idx >= 0; --idx) {
const line = this._document.lineAt(idx).text.trimLeft(); const line = this.document.lineAt(idx).text.trimLeft();
if (!line.startsWith('@')) { if (!line.startsWith('@')) continue;
continue;
}
if (!verbatim) { if (!verbatim) {
if (line === '@bye') { if (line === '@bye') {
lastLine = idx; lastLine = idx;
// Abort anything after `@bye`. // Abort anything after `@bye`.
this._foldingRanges = []; this._foldingRanges = [];
closingBlocks = []; closingBlocks = [];
this._clearTemporaries(); this.clearTemporaries();
continue;
}
if (this._processComment(line, idx)) {
continue; continue;
} }
if (this.processComment(line, idx)) continue;
} }
// Process block. // Process block.
if (line.startsWith('@end ')) { if (line.startsWith('@end ')) {
if (verbatim) { if (verbatim) continue;
continue;
}
const name = line.substring(5).trimRight(); const name = line.substring(5).trimRight();
if (name === 'verbatim') { if (name === 'verbatim') {
verbatim = true; verbatim = true;
@ -159,123 +141,93 @@ export default class FoldingRangeContext
closingBlocks.push({ name: name, line: idx }); closingBlocks.push({ name: name, line: idx });
continue; continue;
} }
if (!verbatim && this._processNode(line, idx, lastLine)) { if (!verbatim && this.processNode(line, idx, lastLine)) continue;
continue;
}
const closingBlock = closingBlocks.pop(); const closingBlock = closingBlocks.pop();
if (closingBlock === undefined) { if (closingBlock === undefined) continue;
continue; if (line.substring(1, closingBlock.name.length + 2).trim() === closingBlock.name) {
} this.addRange(idx, closingBlock.line, { name: closingBlock.name });
const name = closingBlock.name; // If `verbatim == true` goes here, this line must be the `@verbatim` line.
if (line.substring(1, name.length + 2).trim() === name) {
this._addRange(idx, closingBlock.line, { name: name });
// If `verbatim == true` goes here,
// this line must be the `@verbatim` line.
verbatim = false; verbatim = false;
} else { } else {
closingBlocks.push(closingBlock); closingBlocks.push(closingBlock);
} }
} }
if (this._commentRange !== undefined) { if (this.commentRange !== undefined) {
this._addRange( this.addRange(this.commentRange.start, this.commentRange.end, { kind: vscode.FoldingRangeKind.Comment });
this._commentRange.start,
this._commentRange.end,
{ kind: vscode.FoldingRangeKind.Comment },
);
} }
return this._foldingRanges; return this._foldingRanges;
} }
private _clearTemporaries() { private clearTemporaries() {
this._commentRange = undefined; this.commentRange = undefined;
this._headerStart = undefined; this.headerStart = undefined;
this._nodes = []; this.nodes = [];
this._closingSubsection = this._closingSection = this._closingChapter this.closingSubsection = this.closingSection = this.closingChapter = undefined;
= undefined;
} }
private _getLastTextLine(lineNum: number, limit = 3) { private getLastTextLine(lineNum: number, limit = 3) {
for (let idx = lineNum; idx > lineNum - limit; --idx) { for (let idx = lineNum; idx > lineNum - limit; --idx) {
const line = this._document.lineAt(idx).text; const line = this.document.lineAt(idx).text;
if (line.startsWith('@node ')) { if (line.startsWith('@node ')) return idx - 1;
return idx - 1; if (line === '') return idx;
}
if (line === '') {
return idx;
}
} }
return lineNum; return lineNum;
} }
private _processComment(lineText: string, lineNum: number) { private processComment(lineText: string, lineNum: number) {
if (!lineText.startsWith('@c')) { if (!lineText.startsWith('@c')) return false;
return false; if (!lineText.startsWith(' ', 2) && !lineText.startsWith('omment ', 2)) {
}
if (lineText.charAt(2) != ' ' && !lineText.startsWith('omment ', 2)) {
return false; return false;
} }
// Check for opening/closing header. // Check for opening/closing header.
if (lineText.startsWith('%**', lineText[2] === ' ' ? 3 : 9)) { if (lineText.startsWith('%**', lineText[2] === ' ' ? 3 : 9)) {
if (this._headerStart === undefined) { if (this.headerStart === undefined) {
this._headerStart = lineNum; this.headerStart = lineNum;
} else { } else {
this._addRange(lineNum, this._headerStart, this.addRange(lineNum, this.headerStart, { kind: vscode.FoldingRangeKind.Region });
{ kind: vscode.FoldingRangeKind.Region }); this.headerStart = undefined;
this._headerStart = undefined;
} }
return true; return true;
} }
if (this._commentRange === undefined) { if (this.commentRange === undefined) {
this._commentRange = { start: lineNum, end: lineNum }; this.commentRange = { start: lineNum, end: lineNum };
} else if (this._commentRange.start - 1 === lineNum) { } else if (this.commentRange.start - 1 === lineNum) {
this._commentRange.start = lineNum; this.commentRange.start = lineNum;
} else { } else {
this._addRange(this._commentRange.start, this._commentRange.end, this.addRange(this.commentRange.start, this.commentRange.end, { kind: vscode.FoldingRangeKind.Comment });
{ kind: vscode.FoldingRangeKind.Comment }); this.commentRange = undefined;
this._commentRange = undefined;
} }
return true; return true;
} }
private _processNode( private processNode(lineText: string, lineNum: number, lastLineNum: number) {
lineText: string, const result = lineText.match(FoldingRangeContext.nodeFormat);
lineNum: number, if (result === null) return false;
lastLineNum: number,
) {
const result = lineText.match(FoldingRangeContext._nodeFormat);
if (result === null) {
return false;
}
// Node identifier. // Node identifier.
if (result[1] !== undefined) { if (result[1] !== undefined) {
this._nodes.push(new vscode.CodeLens(lineNumToRange(lineNum), { this.nodes.push(new vscode.CodeLens(lineNumToRange(lineNum), {
title: '$(go-to-file) Goto node in preview', title: '$(go-to-file) Goto node in preview',
command: 'texinfo.preview.goto', command: 'texinfo.preview.goto',
arguments: [this._document, result[5]], arguments: [this.document, result[5]],
})); }));
return true; return true;
} }
// Subsection level node. // Subsection level node.
if (result[2] !== undefined) { if (result[2] !== undefined) {
this._addRange(lineNum, this._closingSubsection ?? lastLineNum, this.addRange(lineNum, this.closingSubsection ?? lastLineNum, { name: result[2], detail: result[5] });
{ name: result[2], detail: result[5] }); this.closingSubsection = this.getLastTextLine(lineNum - 1);
this._closingSubsection = this._getLastTextLine(lineNum - 1);
return true; return true;
} }
// Section level node. // Section level node.
if (result[3] !== undefined) { if (result[3] !== undefined) {
this._addRange(lineNum, this._closingSection ?? lastLineNum, this.addRange(lineNum, this.closingSection ?? lastLineNum, { name: result[3], detail: result[5] });
{ name: result[3], detail: result[5] }); this.closingSubsection = this.closingSection = this.getLastTextLine(lineNum - 1);
this._closingSubsection = this._closingSection
= this._getLastTextLine(lineNum - 1);
return true; return true;
} }
// Chapter level node. // Chapter level node.
if (result[4] !== undefined) { if (result[4] !== undefined) {
this._addRange(lineNum, this._closingChapter ?? lastLineNum, this.addRange(lineNum, this.closingChapter ?? lastLineNum, { name: result[4], detail: result[5] });
{ name: result[4], detail: result[5] }); this.closingSubsection = this.closingSection = this.closingChapter = this.getLastTextLine(lineNum - 1);
this._closingSubsection = this._closingSection
= this._closingChapter = this._getLastTextLine(lineNum - 1);
return true; return true;
} }
return false; return false;

View File

@ -28,108 +28,85 @@ import { getNodeHtmlRef, prompt } from '../utils/misc';
/** /**
* Stores information of a Texinfo document preview. * Stores information of a Texinfo document preview.
*/ */
export default class PreviewContext export default class PreviewContext {
{
close() { close() {
this._disposables.forEach(event => event.dispose()); this.disposables.forEach(event => event.dispose());
this._panel.dispose(); this.panel.dispose();
this._documentContext.closePreview(); this.documentContext.closePreview();
// Only show diagnostic information when the preview is active. // Only show diagnostic information when the preview is active.
this._diagnosis.delete(this._document); this.diagnosis.delete(this.document);
} }
goto(nodeName: string) { goto(nodeName: string) {
const message = { command: 'goto', value: getNodeHtmlRef(nodeName) }; this.panel.webview.postMessage({ command: 'goto', value: getNodeHtmlRef(nodeName) });
this._webview.postMessage(message);
} }
show() { show() {
this._panel.reveal(); this.panel.reveal();
} }
async updateWebview() { async updateWebview() {
if (this._updating) { if (this.updating) {
this._pendingUpdate = true; this.pendingUpdate = true;
return; return;
} }
this._updating = true; this.updating = true;
this._pendingUpdate = false; this.pendingUpdate = false;
// Inform the user that the preview is updating, when `makeinfo` // Inform the user that the preview is updating if `makeinfo` takes too long.
// takes too long. setTimeout(() => this.updating && this.updateTitle(), 500);
setTimeout(() => this._updating && this._updateTitle(), 500); const initFile = this.globalContext.extensionPath + '/ext/html-preview.pm';
const converter = new Converter( const converter = new Converter(this.document.fileName, initFile, this.globalContext.options, this.logger);
this._document.fileName, const { data, error } = await converter.toHTML(path => this.panel.webview.asWebviewUri(path), this.script);
this._globalContext.path + '/ext/html-preview.pm',
this._globalContext.options,
this._logger,
);
const { data, error } = await converter.toHTML(
path => this._webview.asWebviewUri(path),
this._script,
);
if (error) { if (error) {
this._logger.log(error); this.logger.log(error);
this._diagnosis.update(this._document, error); this.diagnosis.update(this.document, error);
} else { } else {
this._diagnosis.delete(this._document); this.diagnosis.delete(this.document);
} }
if (data === undefined) { if (data === undefined) {
prompt(`Failed to show preview for ${this._document.fileName}.`, prompt(`Failed to show preview for ${this.document.fileName}.`, 'Show log', true)
'Show log', true) .then(result => result && this.logger.show());
.then(result => result && this._logger.show());
} else { } else {
this._webview.html = data; this.panel.webview.html = data;
} }
this._updating = false; this.updating = false;
this._updateTitle(); this.updateTitle();
this._pendingUpdate && this.updateWebview(); this.pendingUpdate && this.updateWebview();
} }
constructor(private readonly _documentContext: DocumentContext) { constructor(private readonly documentContext: DocumentContext) {
const options = { this.panel = vscode.window.createWebviewPanel('texinfo.preview', '', vscode.ViewColumn.Beside,
enableFindWidget: true, { enableFindWidget: true, retainContextWhenHidden: true, enableScripts: true });
retainContextWhenHidden: true, this.disposables.push(this.panel.onDidDispose(() => this.close()));
enableScripts: true, this.updateTitle();
};
this._panel = vscode.window.createWebviewPanel(
'texinfo.preview', '',
vscode.ViewColumn.Beside,
options,
);
this._webview = this._panel.webview;
this._disposables.push(this._panel.onDidDispose(() => this.close()));
this._updateTitle();
this.updateWebview(); this.updateWebview();
} }
private readonly _document = this._documentContext.document; private readonly document = this.documentContext.document;
private readonly _globalContext = this._documentContext.globalContext; private readonly globalContext = this.documentContext.globalContext;
private readonly _diagnosis = this._globalContext.diagnosis; private readonly diagnosis = this.globalContext.diagnosis;
private readonly _logger = this._globalContext.logger; private readonly logger = this.globalContext.logger;
private readonly _disposables = <vscode.Disposable[]>[]; private readonly disposables = <vscode.Disposable[]>[];
private readonly _panel: vscode.WebviewPanel; private readonly panel: vscode.WebviewPanel;
private readonly _webview: vscode.Webview;
/** /**
* Whether a preview update request is pending. * Whether a preview update request is pending.
*/ */
private _pendingUpdate = false; private pendingUpdate = false;
/** /**
* Whether the preview is updating. * Whether the preview is updating.
*/ */
private _updating = false; private updating = false;
/** /**
* Generate script used for jumping to the corresponding location of * Generate script used for jumping to the corresponding location of preview with code lens.
* preview with code lens.
*/ */
private get _script() { private get script() {
if (!this._globalContext.options.enableCodeLens) { if (!this.globalContext.options.enableCodeLens) return undefined;
return undefined;
}
return "window.addEventListener('message', event => {" + return "window.addEventListener('message', event => {" +
"const message = event.data;" + "const message = event.data;" +
"switch (message.command) {" + "switch (message.command) {" +
@ -142,9 +119,9 @@ export default class PreviewContext
"})"; "})";
} }
private _updateTitle() { private updateTitle() {
const updating = this._updating ? '(Updating) ' : ''; const updating = this.updating ? '(Updating) ' : '';
const fileName = path.basename(this._document.fileName); const fileName = path.basename(this.document.fileName);
this._panel.title = `${updating}Preview ${fileName}`; this.panel.title = `${updating}Preview ${fileName}`;
} }
} }

View File

@ -19,23 +19,22 @@
* vscode-texinfo. If not, see <https://www.gnu.org/licenses/>. * vscode-texinfo. If not, see <https://www.gnu.org/licenses/>.
*/ */
import * as path from 'path';
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import { escapeStringForRegExp, lineNumToRange } from './utils/misc'; import { lineNumToRange } from './utils/misc';
import { isDefined } from './utils/types'; import { isDefined } from './utils/types';
/** /**
* Manage diagnostic information of Texinfo documents. * Manage diagnostic information of Texinfo documents.
*/ */
export default class Diagnosis implements vscode.Disposable export default class Diagnosis implements vscode.Disposable {
{
/** /**
* Remove a document's diagnostic entry from the collection. * Remove a document's diagnostic entry from the collection.
* *
* @param document * @param document
*/ */
delete(document: vscode.TextDocument) { delete(document: vscode.TextDocument) {
this._diagnostics.delete(document.uri); this.diagnostics.delete(document.uri);
} }
/** /**
@ -45,29 +44,19 @@ export default class Diagnosis implements vscode.Disposable
* @param logText * @param logText
*/ */
update(document: vscode.TextDocument, logText: string) { update(document: vscode.TextDocument, logText: string) {
const fileName = path.basename(document.uri.path); const fileName = document.uri.path;
const regex = new RegExp(`${escapeStringForRegExp(fileName)}:\\d+:`);
const diagnostics = logText.split('\n') const diagnostics = logText.split('\n')
.map(line => line.length > 0 ? line.match(regex) : null) .filter(line => line.startsWith(fileName))
.map(result => { .map(line => logLineToDiagnostic(line.substring(fileName.length + 1)))
const index = result?.index;
const line = result?.input;
if (index === undefined || line === undefined) {
return undefined;
}
const logText = line.substring(index + fileName.length + 1);
return logToDiagnostic(logText);
})
.filter(isDefined); .filter(isDefined);
this._diagnostics.set(document.uri, diagnostics); this.diagnostics.set(document.uri, diagnostics);
} }
dispose() { dispose() {
this._diagnostics.dispose(); this.diagnostics.dispose();
} }
private readonly _diagnostics private readonly diagnostics = vscode.languages.createDiagnosticCollection('texinfo');
= vscode.languages.createDiagnosticCollection('texinfo');
} }
/** /**
@ -76,15 +65,11 @@ export default class Diagnosis implements vscode.Disposable
* @param lineText * @param lineText
* @returns * @returns
*/ */
function logToDiagnostic(lineText: string) { function logLineToDiagnostic(lineText: string) {
const lineNum = parseInt(lineText) - 1; const lineNum = parseInt(lineText) - 1;
// Ignore error that does not correspond to a line in document. // Ignore error that does not correspond a line in document.
if (isNaN(lineNum)) { if (isNaN(lineNum)) return undefined;
return undefined;
}
const message = lineText.substring(lineNum.toString().length + 2); const message = lineText.substring(lineNum.toString().length + 2);
const severity = message.startsWith('warning:') const severity = message.startsWith('warning:') ? vscode.DiagnosticSeverity.Warning : undefined;
? vscode.DiagnosticSeverity.Warning
: undefined;
return new vscode.Diagnostic(lineNumToRange(lineNum), message, severity); return new vscode.Diagnostic(lineNumToRange(lineNum), message, severity);
} }

View File

@ -33,54 +33,33 @@ import FoldingRangeProvider from './providers/folding_range';
/** /**
* Manage extension-level global-scope contexts. * Manage extension-level global-scope contexts.
*/ */
export default class GlobalContext export default class GlobalContext {
{
readonly contextMapping = new ContextMapping(this); readonly contextMapping = new ContextMapping(this);
readonly diagnosis = new Diagnosis; readonly diagnosis = new Diagnosis;
readonly indicator = new Indicator(this); readonly indicator = new Indicator(this);
readonly logger = new Logger; readonly logger = new Logger;
readonly path = this._context.extensionPath; readonly extensionPath = this.context.extensionPath;
/** /**
* Note: `Options`' no singleton. * Note: `Options`' no singleton. Do not wire directly, always use `globalContext.options` instead.
*
* Do not wire directly, always use `globalContext.options` instead.
*/ */
get options() { get options() {
return this._options ??= new Options; return this._options ??= new Options;
} }
subscribe(...items: vscode.Disposable[]) { subscribe(...items: vscode.Disposable[]) {
this._context.subscriptions.push(...items); this.context.subscriptions.push(...items);
} }
constructor(private readonly _context: vscode.ExtensionContext) { constructor(private readonly context: vscode.ExtensionContext) {
this.subscribe( this.subscribe(this.contextMapping, this.diagnosis, this.indicator, this.logger,
this.contextMapping, vscode.languages.registerCodeLensProvider('texinfo', new CodeLensProvider(this)),
this.diagnosis, vscode.languages.registerCompletionItemProvider('texinfo', new CompletionItemProvider(this), '@'),
this.indicator, vscode.languages.registerDocumentSymbolProvider('texinfo', new DocumentSymbolProvider(this)),
this.logger, vscode.languages.registerFoldingRangeProvider('texinfo', new FoldingRangeProvider(this)),
vscode.languages.registerCodeLensProvider( vscode.workspace.onDidChangeConfiguration(() => this._options = undefined),
'texinfo',
new CodeLensProvider(this),
),
vscode.languages.registerCompletionItemProvider(
'texinfo',
new CompletionItemProvider(this),
'@',
),
vscode.languages.registerDocumentSymbolProvider(
'texinfo',
new DocumentSymbolProvider(this),
),
vscode.languages.registerFoldingRangeProvider(
'texinfo',
new FoldingRangeProvider(this),
),
vscode.workspace.onDidChangeConfiguration(
() => this._options = undefined,
),
); );
} }

View File

@ -1,7 +1,7 @@
/** /**
* indicator.ts * indicator.ts
* *
* Copyright (C) 2020,2021,2024 CismonX <admin@cismon.net> * Copyright (C) 2020,2021 CismonX <admin@cismon.net>
* *
* This file is part of vscode-texinfo. * This file is part of vscode-texinfo.
* *
@ -26,41 +26,34 @@ import { exec } from './utils/misc';
/** /**
* Shows whether GNU Texinfo is properly installed and configured. * Shows whether GNU Texinfo is properly installed and configured.
*/ */
export default class Indicator implements vscode.Disposable export default class Indicator implements vscode.Disposable {
{
get canDisplayPreview() { get canDisplayPreview() {
return this._canDisplayPreview; return this._canDisplayPreview;
} }
dispose() { dispose() {
this._statusBarItem.dispose(); this.statusBarItem.dispose();
} }
constructor(private readonly _globalContext: GlobalContext) { constructor(private readonly globalContext: GlobalContext) {
_globalContext.subscribe( globalContext.subscribe(
vscode.commands.registerCommand( vscode.commands.registerCommand('texinfo.indicator.click', this.click.bind(this)),
'texinfo.indicator.click', vscode.window.onDidChangeActiveTextEditor(this.refresh.bind(this)),
this._click.bind(this),
),
vscode.window.onDidChangeActiveTextEditor(
this._refresh.bind(this),
),
); );
this._updateStatus() this.updateStatus().then(() => this.refresh(vscode.window.activeTextEditor));
.then(() => this._refresh(vscode.window.activeTextEditor));
} }
private _canDisplayPreview = false; private _canDisplayPreview = false;
private readonly _statusBarItem = vscode.window.createStatusBarItem( private readonly statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
vscode.StatusBarAlignment.Right, 100);
/** /**
* Calls when the status bar item is clicked. * Calls when the status bar item is clicked.
*/ */
private async _click() { private async click() {
await this._updateStatus(); await this.updateStatus();
this._refresh(vscode.window.activeTextEditor); this.refresh(vscode.window.activeTextEditor);
} }
/** /**
@ -68,46 +61,39 @@ export default class Indicator implements vscode.Disposable
* *
* @param editor * @param editor
*/ */
private _refresh(editor?: vscode.TextEditor) { private refresh(editor?: vscode.TextEditor) {
if (editor?.document.languageId === 'texinfo') { if (editor?.document.languageId === 'texinfo') {
this._statusBarItem.show(); this.statusBarItem.show();
} else { } else {
this._statusBarItem.hide(); this.statusBarItem.hide();
} }
} }
/** /**
* Update the installation status of GNU Texinfo, * Update the installation status of GNU Texinfo, by checking `makeinfo --version`.
* by checking `makeinfo --version`.
*/ */
private async _updateStatus() { private async updateStatus() {
const options = this._globalContext.options; const options = this.globalContext.options;
const output const output = await exec(options.makeinfo, ['--version'], options.maxSize);
= await exec(options.makeinfo, ['--version'], options.maxSize);
const result = output.data?.match(/\(GNU texinfo\) (.*)\n/); const result = output.data?.match(/\(GNU texinfo\) (.*)\n/);
const version = result?.[1] ?? ''; let tooltip = '', icon: string, version = '';
let tooltip = '', icon: string; if (result && result[1]) {
if (version) { version = result[1];
icon = '$(check)'; if (!isNaN(+version) && +version < 6.7) {
const verArr = version.split('.');
if (version.length >= 2) {
const verMajor = parseInt(verArr[0], 10);
const verMinor = parseInt(verArr[1], 10);
if (verMajor < 7 || verMinor < 1) {
icon = '$(warning)'; icon = '$(warning)';
tooltip = `GNU Texinfo (${options.makeinfo}) ` + tooltip = `GNU Texinfo (${options.makeinfo}) is outdated (${version} < 6.7).`;
`is outdated (${version} < 7.1).`; } else {
} // Unrecognizable version. Assume it is okay.
icon = '$(check)';
} }
this._canDisplayPreview = true; this._canDisplayPreview = true;
} else { } else {
icon = '$(close)'; icon = '$(close)';
tooltip = `GNU Texinfo (${options.makeinfo}) ` + tooltip = `GNU Texinfo (${options.makeinfo}) is not correctly installed or configured.`;
`is not correctly installed or configured.`;
this._canDisplayPreview = false; this._canDisplayPreview = false;
} }
this._statusBarItem.command = 'texinfo.indicator.click'; this.statusBarItem.command = 'texinfo.indicator.click';
this._statusBarItem.text = `${icon} GNU Texinfo ${version}`; this.statusBarItem.text = `${icon} GNU Texinfo ${version}`;
this._statusBarItem.tooltip = tooltip; this.statusBarItem.tooltip = tooltip;
} }
} }

View File

@ -24,24 +24,20 @@ import * as vscode from 'vscode';
/** /**
* Logger which prints message to VSCode output channel. * Logger which prints message to VSCode output channel.
*/ */
export default class Logger implements vscode.Disposable export default class Logger implements vscode.Disposable {
{
log(message: string) { log(message: string) {
const dateTime = new Date().toLocaleString( const dateTime = new Date().toLocaleString(undefined, { hour12: false });
undefined, this.outputChannel.appendLine(`[ ${dateTime} ]\n${message}`);
{ hour12: false }
);
this._outputChannel.appendLine(`[ ${dateTime} ]\n${message}`);
} }
show() { show() {
this._outputChannel.show(true); this.outputChannel.show(true);
} }
dispose() { dispose() {
this._outputChannel.dispose(); this.outputChannel.dispose();
} }
private readonly _outputChannel private readonly outputChannel = vscode.window.createOutputChannel('Texinfo');
= vscode.window.createOutputChannel('Texinfo');
} }

View File

@ -26,80 +26,75 @@ import * as vscode from 'vscode';
* *
* See the `contributes.configuration` entry in package.json for details. * See the `contributes.configuration` entry in package.json for details.
*/ */
export default class Options export default class Options {
{
get enableSnippets() { get enableSnippets() {
return this._getBoolean('completion.enableSnippets'); return this.getBoolean('completion.enableSnippets');
} }
get hideSnippetCommands() { get hideSnippetCommands() {
return this._getBoolean('completion.hideSnippetCommands'); return this.getBoolean('completion.hideSnippetCommands');
} }
get noWarnings() { get noWarnings() {
return this._getBoolean('diagnosis.noWarnings'); return this.getBoolean('diagnosis.noWarnings');
} }
get enableCodeLens() { get enableCodeLens() {
return this._getBoolean('enableCodeLens'); return this.getBoolean('enableCodeLens');
} }
get makeinfo() { get makeinfo() {
return this._getString('makeinfo'); return this.getString('makeinfo');
} }
get customCSS() { get customCSS() {
return this._getString('preview.customCSS'); return this.getString('preview.customCSS');
} }
get errorLimit() { get errorLimit() {
return this._getNumber('preview.errorLimit'); return this.getNumber('preview.errorLimit');
} }
get includePaths() { get includePaths() {
return this._getArray('preview.includePaths'); return this.getArray('preview.includePaths');
} }
get maxSize() { get maxSize() {
return this._getNumber('preview.maxSize') * 1024 * 1024; return this.getNumber('preview.maxSize') * 1024 * 1024;
} }
get noHeaders() { get noHeaders() {
return this._getBoolean('preview.noHeaders'); return this.getBoolean('preview.noHeaders');
} }
get noNumberSections() { get noNumberSections() {
return this._getBoolean('preview.noNumberSections'); return this.getBoolean('preview.noNumberSections');
} }
get noValidation() { get noValidation() {
return this._getBoolean('preview.noValidation'); return this.getBoolean('preview.noValidation');
} }
get variables() { get variables() {
return this._getArray('preview.variables'); return this.getArray('preview.variables');
} }
get customizationVariables() { private readonly configuration = vscode.workspace.getConfiguration('texinfo');
return this._getArray('preview.customizationVariables');
private getArray(section: string): readonly string[] {
return this.configuration.get(section, []);
} }
private readonly _configuration private getBoolean(section: string) {
= vscode.workspace.getConfiguration('texinfo'); return this.configuration.get(section, false);
private _getArray(section: string): readonly string[] {
return this._configuration.get(section, []);
} }
private _getBoolean(section: string) { private getNumber(section: string) {
return this._configuration.get(section, false); return this.configuration.get(section, 0);
} }
private _getNumber(section: string) { private getString(section: string) {
return this._configuration.get(section, 0); return this.configuration.get(section, '');
}
private _getString(section: string) {
return this._configuration.get(section, '');
} }
} }

View File

@ -25,18 +25,13 @@ import GlobalContext from '../global_context';
/** /**
* Provide code lenses for Texinfo document. * Provide code lenses for Texinfo document.
*/ */
export default class CodeLensProvider implements vscode.CodeLensProvider export default class CodeLensProvider implements vscode.CodeLensProvider {
{
provideCodeLenses(document: vscode.TextDocument) { provideCodeLenses(document: vscode.TextDocument) {
if (!this._globalContext.options.enableCodeLens) { if (!this.globalContext.options.enableCodeLens) return undefined;
return undefined; if (!this.globalContext.indicator.canDisplayPreview) return undefined;
} return this.globalContext.contextMapping.getDocumentContext(document).foldingRange.nodeValues;
if (!this._globalContext.indicator.canDisplayPreview) {
return undefined;
}
return this._globalContext.contextMapping
.getDocumentContext(document).foldingRange.nodeValues;
} }
constructor(private readonly _globalContext: GlobalContext) {} constructor(private readonly globalContext: GlobalContext) {}
} }

File diff suppressed because it is too large Load Diff

View File

@ -25,13 +25,11 @@ import GlobalContext from '../global_context';
/** /**
* Provide document symbol information for Texinfo documents. * Provide document symbol information for Texinfo documents.
*/ */
export default class DocumentSymbolProvider export default class DocumentSymbolProvider implements vscode.DocumentSymbolProvider {
implements vscode.DocumentSymbolProvider
{
provideDocumentSymbols(document: vscode.TextDocument) { provideDocumentSymbols(document: vscode.TextDocument) {
return this._globalContext.contextMapping return this.globalContext.contextMapping.getDocumentContext(document).documentSymbol.documentSymbols;
.getDocumentContext(document).documentSymbol.documentSymbols;
} }
constructor(private readonly _globalContext: GlobalContext) {} constructor(private readonly globalContext: GlobalContext) {}
} }

View File

@ -25,13 +25,11 @@ import GlobalContext from '../global_context';
/** /**
* Provide folding range info for Texinfo documents. * Provide folding range info for Texinfo documents.
*/ */
export default class FoldingRangeProvider export default class FoldingRangeProvider implements vscode.FoldingRangeProvider {
implements vscode.FoldingRangeProvider
{
provideFoldingRanges(document: vscode.TextDocument) { provideFoldingRanges(document: vscode.TextDocument) {
return this._globalContext.contextMapping return this.globalContext.contextMapping.getDocumentContext(document).foldingRange.foldingRanges;
.getDocumentContext(document).foldingRange.foldingRanges;
} }
constructor(private readonly _globalContext: GlobalContext) {} constructor(private readonly globalContext: GlobalContext) {}
} }

View File

@ -23,76 +23,52 @@ import * as path from 'path';
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import Logger from '../logger'; import Logger from '../logger';
import Options from '../options'; import Options from '../options';
import { exec, normalizePath } from './misc'; import { exec } from './misc';
import { Operator } from './types'; import { Operator } from './types';
/** /**
* Converter which converts file from Texinfo to other formats. * Converter which converts file from Texinfo to other formats.
*/ */
export default class Converter export default class Converter {
{
async toHTML(imgTransformer: Operator<vscode.Uri>, insertScript?: string) { async toHTML(imgTransformer: Operator<vscode.Uri>, insertScript?: string) {
const pathUri = vscode.Uri.file(path.dirname(this._pathName) + '/'); const newPath = imgTransformer(vscode.Uri.file(path.dirname(this.path))).toString() + '/';
const newPath = normalizePath(imgTransformer(pathUri).toString()); const options = ['-o-', '--no-split', '--html', `--error-limit=${this.options.errorLimit}`,
const options = ['-o-', '--no-split', '--html', `--init-file=${this.initFile}`, '-D', `__vscode_texinfo_image_uri_base ${newPath}`];
`--error-limit=${this._options.errorLimit}`, this.options.noHeaders && options.push('--no-headers');
`--init-file=${this._initFile}`, this.options.noNumberSections && options.push('--no-number-sections');
'-D', `__vscode_texinfo_image_uri_base ${newPath}`, this.options.noValidation && options.push('--no-validate');
]; this.options.noWarnings && options.push('--no-warn');
this._options.noHeaders && options.push('--no-headers'); insertScript !== undefined && options.push('-c', `EXTRA_HEAD <script>${insertScript}</script>`);
this._options.noNumberSections && options.push('--no-number-sections'); this.addIncludePaths(this.options.includePaths, options);
this._options.noValidation && options.push('--no-validate'); this.defineVariables(this.options.variables, options);
this._options.noWarnings && options.push('--no-warn'); this.includeCustomCSS(this.options.customCSS, options);
if (insertScript !== undefined) { return await exec(this.options.makeinfo, options.concat(this.path), this.options.maxSize);
options.push('-c', `EXTRA_HEAD <script>${insertScript}</script>`);
}
this._addIncludePaths(this._options.includePaths, options);
this._defineVariables(this._options.variables, options);
this._setCustomizationVariables(
this._options.customizationVariables, options);
this._includeCustomCSS(this._options.customCSS, options);
return await exec(
this._options.makeinfo,
options.concat(normalizePath(this._pathName)),
this._options.maxSize,
);
} }
constructor( constructor(
private readonly _pathName: string, private readonly path: string,
private readonly _initFile: string, private readonly initFile: string,
private readonly _options: Options, private readonly options: Options,
private readonly _logger: Logger, private readonly logger: Logger,
) {} ) {}
private _addIncludePaths(paths: readonly string[], options: string[]) { private addIncludePaths(paths: readonly string[], options: string[]) {
if (paths.length === 0) {
return;
}
const separator = process.platform === 'win32' ? ';' : ':'; const separator = process.platform === 'win32' ? ';' : ':';
options.push('-I', paths.join(separator)); options.push('-I', paths.join(separator));
} }
private _defineVariables(variables: readonly string[], options: string[]) { private defineVariables(variables: readonly string[], options: string[]) {
variables.forEach(varName => options.push('-D', varName)); variables.forEach(varName => options.push('-D', varName));
} }
private _setCustomizationVariables( private includeCustomCSS(cssFileURI: string, options: string[]) {
variables: readonly string[], if (!cssFileURI) return;
options: string[],
) {
variables.forEach(varName => options.push('-c', varName));
}
private _includeCustomCSS(cssFileURI: string, options: string[]) {
if (!cssFileURI) {
return;
}
try { try {
const uri = vscode.Uri.parse(cssFileURI, true); const uri = vscode.Uri.parse(cssFileURI, true);
switch (uri.scheme) { switch (uri.scheme) {
case 'file': case 'file':
options.push(`--css-include=${normalizePath(uri.fsPath)}`); options.push(`--css-include=${uri.path}`);
break; break;
case 'http': case 'http':
case 'https': case 'https':
@ -102,8 +78,7 @@ export default class Converter
throw URIError; throw URIError;
} }
} catch (e) { } catch (e) {
this._logger this.logger.log(`Cannot load custom CSS. Invalid URI: '${cssFileURI}'`);
.log(`Cannot load custom CSS. Invalid URI: '${cssFileURI}'`);
} }
} }
} }

View File

@ -20,20 +20,9 @@
*/ */
import * as child_process from 'child_process'; import * as child_process from 'child_process';
import * as path from 'path';
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import { ExecResult } from './types'; import { ExecResult } from './types';
/**
* Escape string to match verbatim in regular expression.
*
* @param str The string to be escaped.
* @returns The escaped string.
*/
export function escapeStringForRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/** /**
* Execute command and fetch output. * Execute command and fetch output.
* *
@ -43,18 +32,9 @@ export function escapeStringForRegExp(str: string) {
* @returns The output data, or `undefined` if execution fails. * @returns The output data, or `undefined` if execution fails.
*/ */
export function exec(path: string, args: string[], maxBuffer: number) { export function exec(path: string, args: string[], maxBuffer: number) {
return new Promise<ExecResult>( return new Promise<ExecResult>(resolve => child_process.execFile(path, args,
resolve => child_process.execFile(path, args, { env: { ...process.env, LC_MESSAGES: 'en_US' }, maxBuffer: maxBuffer }, (error, stdout, stderr) =>
{ resolve(error ? { error: stderr ? stderr : error.message } : { data: stdout, error: stderr })));
env: { ...process.env, LC_MESSAGES: 'en_US.UTF-8' },
maxBuffer: maxBuffer,
},
(error, stdout, stderr) => resolve(error
? { error: stderr ? stderr : error.message }
: { data: stdout, error: stderr }
)
)
);
} }
/** /**
@ -66,8 +46,7 @@ export function exec(path: string, args: string[], maxBuffer: number) {
* @returns Whether the user clicked the button. * @returns Whether the user clicked the button.
*/ */
export async function prompt(message: string, label: string, error = false) { export async function prompt(message: string, label: string, error = false) {
const func = error ? const func = error ? vscode.window.showErrorMessage : vscode.window.showInformationMessage;
vscode.window.showErrorMessage : vscode.window.showInformationMessage;
return label === await func(message, label); return label === await func(message, label);
} }
@ -89,8 +68,7 @@ export function lineNumToRange(startLine: number, endLine = startLine) {
* @param charCode ASCII code of character. * @param charCode ASCII code of character.
*/ */
export function isAlpha(charCode: number) { export function isAlpha(charCode: number) {
return (charCode >= 97 && charCode <= 122) return charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90;
|| (charCode >= 65 && charCode <= 90);
} }
/** /**
@ -99,17 +77,16 @@ export function isAlpha(charCode: number) {
* @param charCode ASCII code of character. * @param charCode ASCII code of character.
*/ */
export function isAlnum(charCode: number) { export function isAlnum(charCode: number) {
return isAlpha(charCode) || (charCode >= 48 && charCode <= 57); return isAlpha(charCode) || charCode >= 48 && charCode <= 57;
} }
/** /**
* Get corresponding HTML cross-reference name by node name. * Get corresponding HTML cross-reference name by node name.
* *
* See section *HTML Cross-reference Node Name Expansion* in the * See section *HTML Cross-reference Node Name Expansion* in the Texinfo manual.
* GNU Texinfo manual.
* *
* TODO: Node name is not displayed verbatim, leading to wrong HTML xref when * TODO: Node name is not displayed verbatim, leading to wrong HTML xref when containing commands.
* containing commands. Fix this when migrating to LSP. * Fix this when migrating to LSP.
* *
* @param nodeName * @param nodeName
*/ */
@ -123,22 +100,5 @@ export function getNodeHtmlRef(nodeName: string) {
.join('')) .join(''))
.join('-'); .join('-');
const firstCharCode = result.charCodeAt(0); const firstCharCode = result.charCodeAt(0);
return isAlpha(firstCharCode) return isAlpha(firstCharCode) ? result : 'g_t_00' + firstCharCode.toString(16) + result.substring(1);
? result
: 'g_t_00' + firstCharCode.toString(16) + result.substring(1);
}
export function normalizePath(pathName: string) {
pathName = path.normalize(pathName);
if (process.platform === 'win32') {
// On Windows, when passing the path of input file to makeinfo,
// using backslashes in path name breaks some other command line
// options (notably, -I).
// Not sure if this is a bug of makeinfo, or perl, or neither.
//
// TODO: We should look into this issue sometime later.
return pathName.replace(/\\/g, '/');
} else {
return pathName;
}
} }

View File

@ -21,33 +21,19 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
export type CompletionItem = vscode.CompletionItem & { export type CompletionItem = vscode.CompletionItem & { snippet?: boolean };
snippet?: boolean,
};
export type ExecResult = { export type ExecResult = { data?: string, error: string };
data?: string,
error: string,
};
export type FoldingRange = vscode.FoldingRange & { export type FoldingRange = vscode.FoldingRange & { name: string, detail: string };
name: string,
detail: string,
};
export type NamedLine = { export type NamedLine = { name: string, line: number };
name: string,
line: number,
};
export type Operator<T> = (arg: T) => T; export type Operator<T> = (arg: T) => T;
export type Optional<T> = T | undefined; export type Optional<T> = T | undefined;
export type Range = { export type Range = { start: number, end: number };
start: number,
end: number,
};
export function isDefined<T>(value: Optional<T>): value is T { export function isDefined<T>(value: Optional<T>): value is T {
return value !== undefined; return value !== undefined;

View File

@ -7,7 +7,8 @@
*/ */
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2021", "module": "CommonJS",
"target": "ES2019",
"outDir": "out", "outDir": "out",
"esModuleInterop": true, "esModuleInterop": true,
"strictNullChecks": true, "strictNullChecks": true,

View File

@ -19,15 +19,13 @@ const config: webpack.Configuration = {
output: { output: {
path: path.resolve(__dirname, 'out'), path: path.resolve(__dirname, 'out'),
filename: 'extension.js', filename: 'extension.js',
library: { libraryTarget: 'commonjs2',
type: "commonjs2",
},
devtoolModuleFilenameTemplate: '../[resource-path]', devtoolModuleFilenameTemplate: '../[resource-path]',
}, },
devtool: isProduction ? false : 'source-map', devtool: isProduction ? false : 'source-map',
optimization: { optimization: {
concatenateModules: true, concatenateModules: true,
minimize: isProduction, minimize: true,
minimizer: [ minimizer: [
new TerserPlugin({ new TerserPlugin({
extractComments: false, extractComments: false,
@ -41,9 +39,6 @@ const config: webpack.Configuration = {
}, },
mangle: { mangle: {
module: true, module: true,
properties: {
regex: /^_/,
},
}, },
}, },
}), }),