├── _extensions └── qformat │ ├── _extension.yml │ └── qformat.lua ├── SECURITY.md ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── feature.md │ ├── question.md │ └── bug.md ├── CONTRIBUTING.md └── CODE_OF_CONDUCT.md ├── .gitignore ├── LICENSE.md ├── README.md └── docs └── images └── qformat.svg /_extensions/qformat/_extension.yml: -------------------------------------------------------------------------------- 1 | title: Formatting support 2 | author: Richard Iannone 3 | version: 0.0.1 4 | quarto-required: ">=1.2.0" 5 | contributes: 6 | shortcodes: 7 | - qformat.lua -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | Should you find a security vulnerability anywhere in this repository, 6 | please send an email to riannone@me.com with a detailed description. 7 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | Thank you for contributing to **qformat**! To make this process easier for everyone, please explain the context and purpose of your contribution. Also, list the changes made to the existing code or documentation. 4 | 5 | # Related GitHub Issues and PRs 6 | 7 | - Ref: # 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Lua sources 2 | luac.out 3 | 4 | # luarocks build files 5 | *.src.rock 6 | *.zip 7 | *.tar.gz 8 | 9 | # Object files 10 | *.o 11 | *.os 12 | *.ko 13 | *.obj 14 | *.elf 15 | 16 | # Precompiled Headers 17 | *.gch 18 | *.pch 19 | 20 | # Libraries 21 | *.lib 22 | *.a 23 | *.la 24 | *.lo 25 | *.def 26 | *.exp 27 | 28 | # Shared objects (inc. Windows DLLs) 29 | *.dll 30 | *.so 31 | *.so.* 32 | *.dylib 33 | 34 | # Executables 35 | *.exe 36 | *.out 37 | *.app 38 | *.i*86 39 | *.x86_64 40 | *.hex 41 | 42 | # Additional files and directories 43 | /.luarc.json 44 | *_files 45 | *.html 46 | *.qmd 47 | .vscode/settings.json 48 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: New feature 3 | about: Suggest a new feature. 4 | title: '' 5 | labels: 'Type: ★ Enhancement' 6 | assignees: rich-iannone 7 | --- 8 | 9 | ## Prework 10 | 11 | - [ ] Read and abide by **qformat**'s [code of conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html) and [contributing guidelines](https://github.com/rich-iannone/qformat/blob/main/.github/CONTRIBUTING.md). 12 | - [ ] Search for duplicates among the [existing issues](https://github.com/rich-iannone/qformat/issues) (both open and closed). 13 | 14 | ## Proposal 15 | 16 | Describe the new feature clearly and concisely. If applicable, write a minimal example to show input, usage, and desired output. 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Ask a question. 4 | title: '' 5 | labels: 'Type: ⁇ Question' 6 | assignees: '' 7 | --- 8 | 9 | ## Prework 10 | 11 | * [ ] Read and agree to the [code of conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html) and [contributing guidelines](https://github.com/rich-iannone/qformat/blob/main/.github/CONTRIBUTING.md). 12 | * [ ] If there is [already a relevant issue](https://github.com/rich-iannone/qformat/issues), whether open or closed, comment on the existing thread instead of posting a new issue. 13 | * [ ] For any problems you identify, add a reproducible example so the maintainer can troubleshoot. A reproducible example is: 14 | * [ ] **Runnable**: post enough code and data so any onlooker can create the error on their own computer. 15 | * [ ] **Minimal**: reduce runtime wherever possible and remove complicated details that are irrelevant to the issue at hand. 16 | 17 | ## Question 18 | 19 | What would you like to know? 20 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Richard Iannone 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug 3 | about: Something is wrong with qformat. 4 | title: '' 5 | labels: 'Type: ☹︎ Bug' 6 | assignees: rich-iannone 7 | --- 8 | 9 | ## Prework 10 | 11 | * [ ] Read and agree to the [code of conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html) and [contributing guidelines](https://github.com/rich-iannone/qformat/blob/main/.github/CONTRIBUTING.md). 12 | * [ ] If there is [already a relevant issue](https://github.com/rich-iannone/qformat/issues), whether open or closed, comment on the existing thread instead of posting a new issue. 13 | 14 | ## Description 15 | 16 | Describe the bug clearly and concisely. 17 | 18 | ## Reproducible example 19 | 20 | * [ ] Post a reproducible example so the maintainer can troubleshoot the problems you identify. A reproducible example is: 21 | * [ ] **Runnable**: post enough code and data so any onlooker can create the error on their own computer. 22 | * [ ] **Minimal**: reduce runtime wherever possible and remove complicated details that are irrelevant to the issue at hand. 23 | 24 | ## Expected result 25 | 26 | What should have happened? Please be as specific as possible. 27 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Information and Guidelines for Contributing to **qformat** 2 | 3 | There are many ways to contribute to the ongoing development of the **qformat** package. Some contributions can be rather easy to do (e.g., fixing typos, improving documentation, filing issues for feature requests or problems, etc.) whereas other contributions can require more time and patience (like answering questions and submitting pull requests with code changes). Just know that that help provided in any capacity is very much appreciated. :) 4 | 5 | ## Filing Issues 6 | 7 | If you believe you found a bug, create a minimal reproducible example for your posting to the [**qformat** issue tracker](https://github.com/rich-iannone/qformat/issues). Try not to include anything unnecessary, just the minimal amount of code that constitutes the reproducible bug. We will try to verify the bug by running the code in the example provided. The quality of the example will reduce the amount of back-and-forth communication in trying to understand how to execute the code on our systems. 8 | 9 | ### Making Pull Requests 10 | 11 | Should you consider making a pull request (PR), please file an issue first and explain the problem in some detail. If the PR is an enhancement, detail how the change would make things better for package users. Bugfix PRs also require some explanation about the bug and how the proposed fix will remove that bug. A great way to illustrate the bug is to include a reproducible example. While all this upfront work prior to preparing a PR can be time-consuming it opens a line of communication with the package authors and the community, perhaps leading to better enhancement or more effective fixes! 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | License: MIT 6 | Contributor Covenant 7 | 8 |
9 | 10 | The **qformat** [Quarto](https://quarto.org) shortcode extension allows you to easily format values to HTML- and LaTeX-based output formats. 11 | 12 | ## How to Use 13 | 14 | Within the `{{< ` / ` >}}`, this shortcode always begins with the `qformat` command; next, you'd add a subcommand to specify the type of formatting to be done. You can, for instance, format numbers to contain decimals and grouping separators with `{{< qformat num ... >}}`. 15 | 16 | Aside from `num`, the other subcommands are `int` (for integer formatting), `sci` (formatting to scientific notation), and `auto` (allows **qformat** latitude to format the value with less user guidance). Not including a subcommand (i.e., using `{{< qformat ... >}}`) is shorthand for using the `auto` subcommand. 17 | 18 | The `...` is for named arguments that are used by some types of formatting but ignored by others should they be irrelevant. Let's now go through each of the formatting types. 19 | 20 | ### Numeric formatting (`num`) 21 | 22 | Numeric formatting takes the form `{{< qformat num ... >}}`. By default, the number `369234.263` becomes `369,234.26` with the default numeric formatting. Here are the named arguments and their defaults: 23 | 24 | - `decimals` (default: `2`) / The number of decimal places to use 25 | - `use_seps` (default: `true`) / Should digit-grouping separators be used? 26 | - `dec_mark` (default: `"."`) / The character(s) used to signify the decimal mark 27 | - `sep_mark` (default: `","`) / The character(s) used to signify the separator mark 28 | - `pattern` (default: *nil*) / A string-based pattern where '{x}' is the value (other chars are literals) 29 | 30 | Here are some examples: 31 | 32 | `{{< qformat num 369234.263 >}}` -> 369,234.26 33 | 34 | `{{< qformat num 369234.263 decimals=4 >}}` -> 369,234.2630 35 | 36 | `{{< qformat num 369234.263 decimals=0 >}}` -> 369,234 37 | 38 | `{{< qformat num 369234.263 use_seps=false >}}` -> 369234.26 39 | 40 | `{{< qformat num 369234.263 dec_mark=',' sep_mark='.' >}}` -> 369.234,26 41 | 42 | `{{< qformat num 369234.263 pattern='value: {x}' >}}` -> value: 369,234.26 43 | 44 | ### Integer formatting (`int`) 45 | 46 | Integer formatting of the form `{{< qformat num ... >}}` is similar to numeric formatting, though the `decimals` and `dec_mark` arguments are disregarded. The value will be rounded before undergoing formatting. Here are a few examples: 47 | 48 | `{{< qformat int 733744.653 >}}` -> 733,745 49 | 50 | `{{< qformat int 733744.653 use_seps=no >}}` -> 733745 51 | 52 | `{{< qformat int 733744.653 sep_mark=space >}}` -> 733 745 53 | 54 | Some notes are in order. You can use either `"true"`/`"yes"` or `"false"`/`"no"` for those arguments looking for a boolean value. The `sep_mark` argument can take the special keyword `"space"` to mean that you want a single space character for the digit-grouping separator. 55 | 56 | ### Scientific notation (`sci`) 57 | 58 | You can transform numbers to scientific notation by using the form `{{< qformat sci ... >}}`. This type of formatting allows the use of the `decimals`, `dec_mark`, and `pattern` arguments (any other named arguments, if provided, will be disregarded). Here are four examples: 59 | 60 | `{{< qformat sci 13463733744.653 >}}` -> 1.35 × 1010 61 | 62 | `{{< qformat sci 0.00000000000392752 >}}` -> 3.93 × 10-12 63 | 64 | `{{< qformat sci 6.343 >}}` -> 6.34 65 | 66 | `{{< qformat sci 623846 dec_mark="," >}}` -> 6,24 × 105 67 | 68 | Scientific notation typically requires some markup to adhere to the standard; **qformat** detects the render output type (either HTML or LaTeX) and provides the correct formatting. Also, any values between 1 and 10 won't show the exponential part since we'd want to avoid a redundant display of × 100. 69 | 70 | ## Installation 71 | 72 | Enter the following in the terminal when located in the working directory of a Quarto project: 73 | 74 | ```sh 75 | quarto add rich-iannone/qformat 76 | ``` 77 | 78 | This will install the **qformat** extension within the `_extensions` directory (you should see `_extensions/qformat`). Using version control? Check in this directory. 79 | 80 | If you encounter a bug, have usage questions, or want to share ideas to make this package better, feel free to file an [issue](https://github.com/rich-iannone/qformat/issues). 81 | 82 | ## Code of Conduct 83 | 84 | Please note that the **qformat** project is released with a [contributor code of conduct](https://www.contributor-covenant.org/version/2/0/code_of_conduct/). 85 |
By participating in this project you agree to abide by its terms. 86 | 87 | ## 📄 License 88 | 89 | **qformat** is licensed under the MIT license. 90 | See the [`LICENSE.md`](LICENSE.md) file for more details. 91 | 92 | ## 🏛️ Governance 93 | 94 | This project is primarily maintained by [Rich Iannone](https://twitter.com/riannone). -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at riannone@me.com. 63 | All complaints will be reviewed and investigated promptly and fairly. 64 | 65 | All community leaders are obligated to respect the privacy and security of the 66 | reporter of any incident. 67 | 68 | ## Enforcement Guidelines 69 | 70 | Community leaders will follow these Community Impact Guidelines in determining 71 | the consequences for any action they deem in violation of this Code of Conduct: 72 | 73 | ### 1. Correction 74 | 75 | **Community Impact**: Use of inappropriate language or other behavior deemed 76 | unprofessional or unwelcome in the community. 77 | 78 | **Consequence**: A private, written warning from community leaders, providing 79 | clarity around the nature of the violation and an explanation of why the 80 | behavior was inappropriate. A public apology may be requested. 81 | 82 | ### 2. Warning 83 | 84 | **Community Impact**: A violation through a single incident or series of 85 | actions. 86 | 87 | **Consequence**: A warning with consequences for continued behavior. No 88 | interaction with the people involved, including unsolicited interaction with 89 | those enforcing the Code of Conduct, for a specified period of time. This 90 | includes avoiding interactions in community spaces as well as external channels 91 | like social media. Violating these terms may lead to a temporary or permanent 92 | ban. 93 | 94 | ### 3. Temporary Ban 95 | 96 | **Community Impact**: A serious violation of community standards, including 97 | sustained inappropriate behavior. 98 | 99 | **Consequence**: A temporary ban from any sort of interaction or public 100 | communication with the community for a specified period of time. No public or 101 | private interaction with the people involved, including unsolicited interaction 102 | with those enforcing the Code of Conduct, is allowed during this period. 103 | Violating these terms may lead to a permanent ban. 104 | 105 | ### 4. Permanent Ban 106 | 107 | **Community Impact**: Demonstrating a pattern of violation of community 108 | standards, including sustained inappropriate behavior, harassment of an 109 | individual, or aggression toward or disparagement of classes of individuals. 110 | 111 | **Consequence**: A permanent ban from any sort of public interaction within the 112 | community. 113 | 114 | ## Attribution 115 | 116 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 117 | version 2.1, available at 118 | . 119 | 120 | Community Impact Guidelines were inspired by 121 | [Mozilla's code of conduct enforcement ladder][https://github.com/mozilla/inclusion]. 122 | 123 | For answers to common questions about this code of conduct, see the FAQ at 124 | . Translations are available at . 125 | 126 | [homepage]: https://www.contributor-covenant.org 127 | -------------------------------------------------------------------------------- /_extensions/qformat/qformat.lua: -------------------------------------------------------------------------------- 1 | -- Import the 'lpeg' module, required for the `gsub_lpeg()` function defined below 2 | local lpeg = require("lpeg") 3 | 4 | -- Define lpeg-based function to effectively replace `string.gsub()` 5 | local function gsub_lpeg(string, pattern, replacement) 6 | pattern = lpeg.P(pattern) 7 | pattern = lpeg.Cs((pattern / replacement + 1) ^ 0) 8 | return lpeg.match(pattern, string) 9 | end 10 | 11 | local function strsplit(string, delimiter) 12 | local result = {} 13 | local pattern = string.format("([^%s]+)", delimiter) 14 | for substr in string.gmatch(string, pattern) do 15 | table.insert(result, substr) 16 | end 17 | return result 18 | end 19 | 20 | -- Function to detects a match in a string via a pattern 21 | local function grepl(string, pattern) 22 | return string.match(string, pattern) ~= nil 23 | end 24 | 25 | -- Function for checking whether a particular value is nil or an empty string 26 | local function is_empty(value) 27 | return value == nil or value == '' 28 | end 29 | 30 | -- Function for checking whether a particular value is an element within a table 31 | local function in_table(val, table) 32 | for i = 1, #table do 33 | if table[i] == val then 34 | return true 35 | end 36 | end 37 | return false 38 | end 39 | 40 | -- Function for arg-parsing; works with `args` or `kwargs` 41 | local function parse_arg(to_check, key) 42 | local value = pandoc.utils.stringify(to_check[key]) 43 | if not is_empty(value) then 44 | return value 45 | else 46 | return nil 47 | end 48 | end 49 | 50 | local function parse_boolean_kwarg(kwargs, key) 51 | 52 | local kwarg_val = parse_arg(kwargs, key) 53 | 54 | if kwarg_val == nil then 55 | return nil 56 | end 57 | 58 | kwarg_val = string.lower(kwarg_val) 59 | 60 | if in_table(kwarg_val, {"yes", "true"}) then 61 | return true 62 | else 63 | return false 64 | end 65 | end 66 | 67 | -- Function for rounding a number 68 | local function round_num(num) 69 | return math.floor(num + 0.5) 70 | end 71 | 72 | local function format_number_with_separators(number, sep) 73 | local formatted_number = tostring(number) 74 | local dp = (string.find(formatted_number, "%.") or #formatted_number + 1) - 1 75 | for i = dp - 3, 1, -3 do 76 | formatted_number = formatted_number:sub(1, i) .. sep .. formatted_number:sub(i + 1) 77 | end 78 | return formatted_number 79 | end 80 | 81 | return { 82 | ["qformat"] = function(args, kwargs) 83 | 84 | local fmt_type = "auto" 85 | local formatted = "" 86 | 87 | -- Count the number of args 88 | local n_args = #args 89 | 90 | -- If the number of args is greater than two then that's an error 91 | if n_args > 2 then 92 | return "[ qformat errcode #01: Can't have more than two args. ]" 93 | end 94 | 95 | -- If the number of args is zero then that's also an error 96 | if n_args == 0 then 97 | return "[ qformat errcode #02: You must provide some args (up to two). ]" 98 | end 99 | 100 | -- The last arg is assumed to be the value to format 101 | local value = parse_arg(args, n_args) 102 | 103 | -- If there are two args then set the `fmt_type` 104 | if n_args == 2 then 105 | local first_arg = parse_arg(args, 1) 106 | if in_table(first_arg, {"num", "int", "sci", "auto"}) then 107 | fmt_type = tostring(first_arg) 108 | end 109 | end 110 | 111 | -- Change `value` to a number (from a string) 112 | local value = tonumber(value) 113 | local is_negative = value < 0 114 | 115 | if is_negative and type(value) == "number" then 116 | value = math.abs(value) 117 | end 118 | 119 | -- Parse kwargs for `use_seps` 120 | local use_seps = parse_boolean_kwarg(kwargs, "use_seps") 121 | if use_seps == nil then 122 | use_seps = true 123 | end 124 | 125 | -- Parse kwargs for `decimals` 126 | local decimals = parse_arg(kwargs, "decimals") 127 | if decimals == nil then 128 | decimals = 2 129 | else 130 | decimals = tonumber(decimals) 131 | end 132 | 133 | -- Parse kwargs for `sep_mark` 134 | local sep_mark = parse_arg(kwargs, "sep_mark") 135 | if sep_mark == nil then 136 | sep_mark = "," 137 | end 138 | 139 | -- Parse kwargs for `dec_mark` 140 | local dec_mark = parse_arg(kwargs, "dec_mark") 141 | if dec_mark == nil then 142 | dec_mark = "." 143 | end 144 | 145 | -- Parse kwargs for `pattern` 146 | local pattern = parse_arg(kwargs, "pattern") 147 | 148 | -- Determine if a format string is supplied 149 | local fmt_str = parse_arg(kwargs, "fmt") 150 | 151 | if fmt_type == "auto" then 152 | 153 | if fmt_str ~= nil then 154 | formatted = tostring(string.format(fmt_str, value)) 155 | else 156 | formatted = tostring(value) 157 | end 158 | 159 | elseif fmt_type == "num" then 160 | 161 | -- Generate a formatting string (using 'f' for floating point format) 162 | fmt_str = "%." .. decimals .. "f" 163 | 164 | -- Format the value and cast to a string 165 | formatted = tostring(string.format(fmt_str, value)) 166 | 167 | -- Ensure that digit-grouping separators are included as placeholders 168 | if use_seps then 169 | formatted = format_number_with_separators(formatted, "|") 170 | end 171 | 172 | -- Replace the decimal mark if required 173 | if dec_mark ~= "." then 174 | formatted = gsub_lpeg(formatted, ".", dec_mark) 175 | end 176 | 177 | -- Replace digit-grouping separator placeholders with `sep_mark` 178 | if (sep_mark == "space") then 179 | formatted = gsub_lpeg(formatted, "|", " ") 180 | else 181 | formatted = gsub_lpeg(formatted, "|", sep_mark) 182 | end 183 | 184 | -- Use the negative sign appropriate to the output context 185 | if is_negative then 186 | if quarto.doc.is_format("html:js") then 187 | formatted = pandoc.RawInline("html", "\u{2212}" .. formatted) 188 | end 189 | end 190 | 191 | elseif fmt_type == "int" then 192 | 193 | -- Round and truncate the value, then, cast to a string 194 | formatted = tostring(math.floor(round_num(value))) 195 | 196 | -- Ensure that digit-grouping separators are included as placeholders 197 | if use_seps then 198 | formatted = format_number_with_separators(formatted, "|") 199 | end 200 | 201 | -- Replace digit-grouping separator placeholders with `sep_mark` 202 | if (sep_mark == "space") then 203 | formatted = gsub_lpeg(formatted, "|", " ") 204 | else 205 | formatted = gsub_lpeg(formatted, "|", sep_mark) 206 | end 207 | 208 | -- Use the negative sign appropriate to the output context 209 | if is_negative then 210 | if quarto.doc.is_format("html:js") then 211 | formatted = pandoc.RawInline("html", "\u{2212}" .. formatted) 212 | end 213 | end 214 | 215 | elseif fmt_type == "sci" then 216 | 217 | -- Generate a formatting string (using 'e' for exponential format) 218 | fmt_str = "%." .. decimals .. "e" 219 | 220 | -- Format the value and cast to a string 221 | formatted = tostring(string.format(fmt_str, value)) 222 | 223 | -- If the string 'e+00' appears in `formatted`, remove that portion of the formatted value 224 | if grepl(formatted, "e%+00$") then 225 | formatted = gsub_lpeg(formatted, "e+00", "") 226 | end 227 | 228 | -- Replace the decimal mark if required 229 | if dec_mark ~= "." then 230 | formatted = gsub_lpeg(formatted, ".", dec_mark) 231 | end 232 | 233 | -- Split the `formatted` string across the 'e' to get `num_val` and `exp_val` parts; 234 | -- This is eventually generated better formatting in scientific notation across different output 235 | local splits = strsplit(formatted, "e") 236 | 237 | -- It may happen that we receive only a single element in `splits` (in the case where 'e+00' 238 | -- was present and then removed); in that case this portion of code is essentially disregarded 239 | -- since just having a number part will print just fine in HTML and LaTeX 240 | if splits[2] then 241 | 242 | local num_val = splits[1] 243 | local exp_val = splits[2] 244 | 245 | if quarto.doc.is_format("html:js") then 246 | formatted = pandoc.RawInline("html", num_val .. " \u{00D7} " .. "10" .. tonumber(exp_val) .. "") 247 | elseif quarto.doc.is_format("pdf") then 248 | formatted = pandoc.RawInline("tex", num_val .. " \\times 10^{ " .. tonumber(exp_val) .. "}") 249 | end 250 | end 251 | end 252 | 253 | -- If a `pattern` value was provided then substitute the '{x}' in the 254 | -- pattern with the `formatted` value with `gsub_lpeg()` 255 | if pattern then 256 | formatted = gsub_lpeg(pattern, "{x}", formatted) 257 | end 258 | 259 | return formatted 260 | end 261 | } 262 | -------------------------------------------------------------------------------- /docs/images/qformat.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | qformat 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | --------------------------------------------------------------------------------